Skip to main content

mln_engine/camera/
map_view.rs

1//! One view of a map: the camera, size and projection that a map snapshot or a
2//! rendered frame shows.
3
4use mln_style::error::Error;
5use mln_style::geo::{LatLng, WrapMode};
6use mln_style::size::Size;
7use mln_style::types::ProjectionDefinition;
8
9use crate::camera::camera::CameraOptions;
10use crate::camera::camera_limits::{CameraLimits, MAX_FIELD_OF_VIEW, MIN_FIELD_OF_VIEW};
11use crate::camera::constants;
12use crate::camera::mode::ConstrainMode;
13use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
14use crate::camera::transform_state::TransformState;
15use crate::camera::view::{ViewParams, map_offset, zoom_scale};
16use crate::geo::{EdgeInsets, NorthOrientation};
17
18/// A camera with every member set: the camera that a map has, where
19/// [`CameraOptions`] is a change to one.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct Camera {
22    /// The coordinate at the center. It keeps the copy of the world that the
23    /// camera is in, so its longitude can be outside -180 to 180.
24    pub center: LatLng,
25    /// The altitude of the center, in meters above sea level.
26    pub center_altitude: f64,
27    /// Insets from the map's edges. The camera centers within the rest.
28    pub padding: EdgeInsets,
29    pub zoom: f64,
30    /// The rotation from north, in degrees.
31    pub bearing: f64,
32    /// The tilt toward the horizon, in degrees. 0 looks straight down.
33    pub pitch: f64,
34    /// The roll, in degrees.
35    pub roll: f64,
36    /// The vertical field of view, in degrees.
37    pub fov: f64,
38}
39
40impl From<Camera> for CameraOptions {
41    /// Options that set every member of the camera, and no anchor.
42    fn from(camera: Camera) -> Self {
43        CameraOptions {
44            center: Some(camera.center),
45            center_altitude: Some(camera.center_altitude),
46            padding: Some(camera.padding),
47            anchor: None,
48            zoom: Some(camera.zoom),
49            bearing: Some(camera.bearing),
50            pitch: Some(camera.pitch),
51            roll: Some(camera.roll),
52            fov: Some(camera.fov),
53        }
54    }
55}
56
57/// A size in logical pixels, and the physical pixels in each logical pixel.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct LogicalExtent {
60    pub size: Size,
61    pub scale_factor: f64,
62}
63
64impl LogicalExtent {
65    #[must_use]
66    pub fn new(size: Size, scale_factor: f64) -> LogicalExtent {
67        LogicalExtent { size, scale_factor }
68    }
69}
70
71/// How a map orients and constrains its view.
72#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct Viewport {
74    pub north_orientation: NorthOrientation,
75    pub constrain_mode: ConstrainMode,
76    /// Insets that move the vanishing point off the center of the map.
77    pub frustum_offset: EdgeInsets,
78    /// Whether the center stands on the terrain, at its height under the
79    /// center, once that has loaded. The ground decides the altitude, so the
80    /// camera ignores the altitude it is given, such as the style's
81    /// `centerAltitude`: at rest the center stands on the ground, and a
82    /// command eases the altitude onto the ground where it leaves the center.
83    /// When this is off, every camera keeps the altitude it is given. Over
84    /// terrain, a command's eye stays above the ground either way. Without
85    /// terrain it changes nothing. On by default.
86    pub center_clamped_to_ground: bool,
87    /// Whether drags and zooms around a point on the globe turn the bearing,
88    /// so the planet keeps its orientation, and a drag can carry the camera
89    /// over a pole. Off by default: they keep the bearing, as MapLibre GL JS
90    /// does. It changes nothing while the map draws Mercator.
91    pub globe_free_bearing: bool,
92}
93
94impl Default for Viewport {
95    fn default() -> Self {
96        Viewport {
97            north_orientation: NorthOrientation::default(),
98            constrain_mode: ConstrainMode::default(),
99            frustum_offset: EdgeInsets::default(),
100            center_clamped_to_ground: true,
101            globe_free_bearing: false,
102        }
103    }
104}
105
106/// One view of a map: its camera, size, and projection.
107#[derive(Clone, Copy, Debug, PartialEq)]
108pub struct MapView {
109    pub camera: Camera,
110    pub extent: LogicalExtent,
111    /// Sets every member when it comes from a map. A member that a view leaves
112    /// unset takes the default of [`View`](crate::camera::View).
113    pub projection_mode: ProjectionMode,
114    pub viewport: Viewport,
115    /// The style's projection at the camera's zoom. A view from a map never
116    /// names `globe`, which [`to_state`](Self::to_state) resolves at the
117    /// camera's zoom.
118    pub projection: ProjectionDefinition,
119}
120
121impl MapView {
122    /// A transform state that shows exactly this view, to convert coordinates
123    /// for it.
124    ///
125    /// The state takes the camera as it is: it keeps the center's copy of the
126    /// world, and has no bounds and the widest zoom and pitch limits, so no
127    /// constraint of the map that the view came from moves the camera.
128    ///
129    /// `Err` for a view that no transform can show: a camera member that isn't
130    /// finite, a zoom, pitch or field of view outside the limits of every map,
131    /// a padding or frustum offset below zero, an empty size, a scale factor
132    /// that isn't positive, or a skew that isn't finite.
133    pub fn to_state(&self) -> Result<TransformState, Error> {
134        self.validate()?;
135        let camera = &self.camera;
136        let viewport = &self.viewport;
137        let projection = self.projection.at_zoom(camera.zoom);
138        let projection_transition = projection.transition_state();
139        let scale = zoom_scale(camera.zoom);
140        let (x, y) = map_offset(&camera.center, scale, projection_transition > 0.0);
141        let params = ViewParams {
142            size: self.extent.size,
143            frustum_offset: viewport.frustum_offset,
144            north_orientation: viewport.north_orientation,
145            constrain_mode: viewport.constrain_mode,
146            center_clamped_to_ground: viewport.center_clamped_to_ground,
147            globe_free_bearing: viewport.globe_free_bearing,
148            projection_definition: projection,
149            projection_transition,
150            padding: camera.padding,
151            x,
152            y,
153            center_altitude: camera.center_altitude,
154            scale,
155            angle: -mln_style::math::deg2rad(camera.bearing),
156            pitch: mln_style::math::deg2rad(camera.pitch),
157            roll: mln_style::math::deg2rad(camera.roll),
158            fov: mln_style::math::deg2rad(camera.fov),
159            x_skew: self.projection_mode.x_skew.unwrap_or(0.0),
160            y_skew: self.projection_mode.y_skew.unwrap_or(1.0),
161            axonometric: self.projection_mode.axonometric.is_some_and(AxonometricMode::as_bool),
162            center_wrap: WrapMode::Unwrapped,
163            terrain_min_elevation: None,
164        };
165        Ok(TransformState::from_parts(params, CameraLimits::widest()))
166    }
167
168    /// The view that this describes, to draw it or convert coordinates for
169    /// it. `Err`: as [`to_state`](Self::to_state).
170    #[cfg(test)]
171    pub(crate) fn to_view(self) -> Result<crate::camera::view::View, Error> {
172        Ok(self.to_state()?.view().clone())
173    }
174
175    fn validate(&self) -> Result<(), Error> {
176        let camera = &self.camera;
177        let finite = [camera.center_altitude, camera.zoom, camera.bearing, camera.pitch, camera.roll, camera.fov];
178        if !finite.iter().all(|value| value.is_finite()) {
179            return Err(Error::invalid_argument("view camera members must be finite"));
180        }
181        let projection = &self.projection;
182        if !projection.transition.is_finite() {
183            return Err(Error::invalid_argument("view projection transition must be finite"));
184        }
185        let limits = TransformState::default();
186        // The globe lets the zoom fall below the minimum toward the poles.
187        let globe = projection.at_zoom(camera.zoom).transition_state() > 0.0;
188        let min_zoom = limits.min_zoom_at_latitude_with(camera.center.latitude(), globe);
189        if !(min_zoom..=constants::MAX_ZOOM).contains(&camera.zoom)
190            || !(mln_style::math::rad2deg(constants::PITCH_MIN)..=mln_style::math::rad2deg(constants::PITCH_MAX))
191                .contains(&camera.pitch)
192            || !(mln_style::math::rad2deg(MIN_FIELD_OF_VIEW)..=mln_style::math::rad2deg(MAX_FIELD_OF_VIEW))
193                .contains(&camera.fov)
194        {
195            return Err(Error::invalid_argument(
196                "view camera zoom, pitch and field of view must be within the limits of a map",
197            ));
198        }
199        if !valid_insets(&camera.padding) || !valid_insets(&self.viewport.frustum_offset) {
200            return Err(Error::invalid_argument("view padding and frustum offset must be finite and at least 0"));
201        }
202        let extent = &self.extent;
203        if extent.size.is_empty() || !extent.scale_factor.is_finite() || extent.scale_factor <= 0.0 {
204            return Err(Error::invalid_argument("view extent dimensions and scale factor must be positive"));
205        }
206        let mode = &self.projection_mode;
207        if !mode.x_skew.is_none_or(f64::is_finite) || !mode.y_skew.is_none_or(f64::is_finite) {
208            return Err(Error::invalid_argument("view projection skews must be finite"));
209        }
210        Ok(())
211    }
212}
213
214fn valid_insets(insets: &EdgeInsets) -> bool {
215    [insets.top, insets.left, insets.bottom, insets.right].iter().all(|value| value.is_finite() && *value >= 0.0)
216}