Skip to main content

mln_engine/camera/
camera_limits.rs

1//! Where a map's camera may go: its bounds and the zoom and pitch it may take.
2
3use mln_style::constants::DEFAULT_MAX_ZOOM;
4use mln_style::error::Error;
5use mln_style::geo::LatLngBounds;
6
7use crate::camera::constants::{DEFAULT_PITCH_MAX, MAX_ZOOM, MIN_ZOOM, PITCH_MAX, PITCH_MIN};
8
9/// The narrowest field of view a camera may take, in radians.
10pub const MIN_FIELD_OF_VIEW: f64 = 0.1 * std::f64::consts::PI / 180.0;
11/// The widest field of view a camera may take, in radians.
12pub const MAX_FIELD_OF_VIEW: f64 = 150.0 * std::f64::consts::PI / 180.0;
13
14/// The limits a map's camera moves within.
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub struct CameraLimits {
17    /// The area the center stays within.
18    pub bounds: LatLngBounds,
19    pub min_zoom: f64,
20    pub max_zoom: f64,
21    /// The least pitch, in radians.
22    pub min_pitch: f64,
23    /// The most pitch, in radians.
24    pub max_pitch: f64,
25}
26
27impl Default for CameraLimits {
28    fn default() -> Self {
29        CameraLimits {
30            bounds: LatLngBounds::infinite(),
31            min_zoom: MIN_ZOOM,
32            max_zoom: f64::from(DEFAULT_MAX_ZOOM),
33            min_pitch: PITCH_MIN,
34            max_pitch: DEFAULT_PITCH_MAX,
35        }
36    }
37}
38
39impl CameraLimits {
40    /// The widest limits that any map allows.
41    #[must_use]
42    pub(crate) fn widest() -> Self {
43        CameraLimits { max_zoom: MAX_ZOOM, max_pitch: PITCH_MAX, ..CameraLimits::default() }
44    }
45
46    /// These limits with each zoom and pitch clamped to the range that any
47    /// map allows, or `Err` for limits that leave the camera nowhere to go:
48    /// a number that isn't finite, a minimum above its maximum, or invalid
49    /// bounds.
50    pub(crate) fn validated(self) -> Result<Self, Error> {
51        if ![self.min_zoom, self.max_zoom, self.min_pitch, self.max_pitch].iter().all(|value| value.is_finite()) {
52            return Err(Error::invalid_argument("camera limits must be finite"));
53        }
54        if !self.bounds.valid() {
55            return Err(Error::invalid_argument("camera bounds are invalid"));
56        }
57        if self.min_zoom > self.max_zoom {
58            return Err(Error::invalid_argument("the minimum zoom must be at most the maximum zoom"));
59        }
60        if self.min_pitch > self.max_pitch {
61            return Err(Error::invalid_argument("the minimum pitch must be at most the maximum pitch"));
62        }
63        Ok(CameraLimits {
64            bounds: self.bounds,
65            min_zoom: self.min_zoom.clamp(MIN_ZOOM, MAX_ZOOM),
66            max_zoom: self.max_zoom.clamp(MIN_ZOOM, MAX_ZOOM),
67            min_pitch: self.min_pitch.clamp(PITCH_MIN, PITCH_MAX),
68            max_pitch: self.max_pitch.clamp(PITCH_MIN, PITCH_MAX),
69        })
70    }
71}