Skip to main content

mln_engine/camera/
view.rs

1//! One view of a map: what its camera sees, with the matrices that draw it
2//! and convert between the screen and the map.
3
4use std::f64::consts::PI;
5
6use geometry::Point;
7use glam::dcamera::rh::proj::opengl::perspective;
8use glam::{DMat4, DVec2, DVec3, DVec4};
9use mln_style::constants::TILE_SIZE_D;
10use mln_style::error::Error;
11use mln_style::geo::{LatLng, WrapMode};
12use mln_style::size::Size;
13use mln_style::types::ProjectionDefinition;
14
15use crate::camera::camera::FreeCameraOptions;
16use crate::camera::camera_pose::CameraPose;
17use crate::camera::constants::DEFAULT_FOV;
18use crate::camera::map_view::{Camera, LogicalExtent, MapView, Viewport};
19use crate::camera::mode::ConstrainMode;
20use crate::camera::projection::{ProjectionData, mercator_tile_matrix};
21use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
22use crate::camera::tile_coordinate::TileCoordinate;
23use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
24pub use crate::geo::NorthOrientation;
25use crate::geo::constants::M2PI;
26use crate::geo::projection::Projection;
27use crate::geo::{EdgeInsets, ScreenCoordinate};
28use crate::tile::UnwrappedTileID;
29
30/// The largest pitch the Mercator horizon is computed for, in radians. Past
31/// it the distance to the horizon grows without bound, and with it the tiles
32/// the view needs.
33pub(crate) fn max_mercator_horizon_angle() -> f64 {
34    mln_style::math::deg2rad(89.25)
35}
36
37/// `x` rounded to the nearest integer when it is within a billionth of it,
38/// so that a zoom of 13.9999999 draws as 14.
39fn round_for_accuracy(x: f64) -> f64 {
40    let round_x = x.round();
41    let diff = (round_x - x).abs();
42    if diff < 1e-9 && diff > 0.0 { round_x } else { x }
43}
44
45/// The scale of `zoom`: 2 to its power.
46#[must_use]
47pub fn zoom_scale(zoom: f64) -> f64 {
48    round_for_accuracy(2.0f64.powf(zoom))
49}
50
51/// The zoom of `scale`: its base-2 logarithm.
52#[must_use]
53pub fn scale_zoom(scale: f64) -> f64 {
54    round_for_accuracy(scale.log2())
55}
56
57/// The map's offset from the world's center that puts `center` at the
58/// center of a view at `scale`, in pixels: the negated center. The globe's
59/// center can be on a pole, which Mercator's stops short of.
60pub(crate) fn map_offset(center: &LatLng, scale: f64, globe: bool) -> (f64, f64) {
61    let world_size = Projection::world_size(scale);
62    let latitude = mln_style::math::deg2rad(center.latitude());
63    let m = 1.0 - 1e-15;
64    let f = mln_style::math::clamp_f64(latitude.sin(), -m, m);
65    let x = -center.longitude() * (world_size / 360.0);
66    let cc = world_size / M2PI;
67    let y = if globe { cc * latitude.tan().asinh() } else { 0.5 * cc * ((1.0 + f) / (1.0 - f)).ln() };
68    (x, y)
69}
70
71/// The fractional part of `x`, with the sign of `x`.
72fn modf_fraction(x: f64) -> f64 {
73    if x.is_infinite() {
74        return 0.0f64.copysign(x);
75    }
76    (x - x.trunc()).copysign(x)
77}
78
79/// What a view shows, in the units its math works in.
80#[derive(Clone, Copy, Debug, PartialEq)]
81pub(crate) struct ViewParams {
82    pub(crate) size: Size,
83    pub(crate) frustum_offset: EdgeInsets,
84    pub(crate) north_orientation: NorthOrientation,
85    /// The constrain mode of the map the view comes from, which
86    /// [`View::map_view`] reports.
87    pub(crate) constrain_mode: ConstrainMode,
88    /// Whether the center of the map the view comes from stands on its
89    /// terrain, which [`View::map_view`] reports.
90    pub(crate) center_clamped_to_ground: bool,
91    /// Whether drags and zooms on the globe of the map the view comes from
92    /// turn the bearing, which [`View::map_view`] reports.
93    pub(crate) globe_free_bearing: bool,
94    /// The style's projection, as it was last set.
95    pub(crate) projection_definition: ProjectionDefinition,
96    /// 0 is Mercator, 1 is the globe, in between is the transition.
97    pub(crate) projection_transition: f64,
98    pub(crate) padding: EdgeInsets,
99    /// The map's offset from the world's center, in pixels at `scale`: the
100    /// negated center.
101    pub(crate) x: f64,
102    pub(crate) y: f64,
103    /// The center's altitude, in meters. It holds through changes of the
104    /// zoom and the center; the matrices derive its pixels.
105    pub(crate) center_altitude: f64,
106    pub(crate) scale: f64,
107    /// The rotation of the map, in radians counterclockwise: the negated
108    /// bearing.
109    pub(crate) angle: f64,
110    pub(crate) pitch: f64,
111    pub(crate) roll: f64,
112    pub(crate) fov: f64,
113    pub(crate) x_skew: f64,
114    pub(crate) y_skew: f64,
115    pub(crate) axonometric: bool,
116    /// How [`View::camera`] reports the center.
117    pub(crate) center_wrap: WrapMode,
118    /// While terrain draws, the lowest ground near the center, in meters,
119    /// exaggerated; the near and far planes then fit raised ground.
120    pub(crate) terrain_min_elevation: Option<f64>,
121}
122
123impl ViewParams {
124    pub(crate) fn new(constrain_mode: ConstrainMode) -> Self {
125        ViewParams {
126            size: Size::default(),
127            frustum_offset: EdgeInsets::default(),
128            north_orientation: NorthOrientation::Upwards,
129            constrain_mode,
130            center_clamped_to_ground: true,
131            globe_free_bearing: false,
132            projection_definition: ProjectionDefinition::default(),
133            projection_transition: 0.0,
134            padding: EdgeInsets::default(),
135            x: 0.0,
136            y: 0.0,
137            center_altitude: 0.0,
138            scale: 1.0,
139            angle: 0.0,
140            pitch: 0.0,
141            roll: 0.0,
142            fov: DEFAULT_FOV,
143            x_skew: 0.0,
144            y_skew: 1.0,
145            axonometric: false,
146            center_wrap: WrapMode::Unwrapped,
147            terrain_min_elevation: None,
148        }
149    }
150}
151
152/// The matrices of a view, zero while its size is empty or its projection
153/// can't be inverted. The globe's are zero unless it renders the globe.
154#[derive(Clone, Copy, Debug)]
155struct Matrices {
156    projection: DMat4,
157    inv_projection: DMat4,
158    coord: DMat4,
159    /// The inverse of `coord` from the center of the map: it takes a screen
160    /// point to its offset from the center, which keeps the precision that
161    /// the whole world's coordinates would lose.
162    inverted_from_center: DMat4,
163    globe_view_projection: DMat4,
164    inv_globe_view_projection: DMat4,
165    globe_clipping_plane: DVec4,
166    globe_camera_position: DVec3,
167}
168
169impl Matrices {
170    const ZERO: Matrices = Matrices {
171        projection: DMat4::ZERO,
172        inv_projection: DMat4::ZERO,
173        coord: DMat4::ZERO,
174        inverted_from_center: DMat4::ZERO,
175        globe_view_projection: DMat4::ZERO,
176        inv_globe_view_projection: DMat4::ZERO,
177        globe_clipping_plane: DVec4::ZERO,
178        globe_camera_position: DVec3::ZERO,
179    };
180}
181
182/// One view of a map: its camera, size and projection, and the matrices it
183/// draws with. A view never changes: a map that moves its camera makes a new
184/// one.
185///
186/// Angles are in radians. A view with an empty size, or a camera whose
187/// projection can't be inverted, shows nothing.
188#[derive(Clone, Debug)]
189pub struct View {
190    params: ViewParams,
191    matrices: Matrices,
192}
193
194impl PartialEq for View {
195    /// Two views are equal if they show the same: the matrices follow.
196    fn eq(&self, other: &Self) -> bool {
197        self.params == other.params
198    }
199}
200
201impl Default for View {
202    fn default() -> Self {
203        View::new(ViewParams::new(ConstrainMode::HeightOnly))
204    }
205}
206
207impl View {
208    pub(crate) fn new(params: ViewParams) -> Self {
209        let mut view = View { params, matrices: Matrices::ZERO };
210        view.matrices = view.compute_matrices();
211        view
212    }
213
214    pub(crate) fn params(&self) -> &ViewParams {
215        &self.params
216    }
217
218    /// The matrices, from the view's parameters alone.
219    fn compute_matrices(&self) -> Matrices {
220        if self.params.size.is_empty() {
221            return Matrices::ZERO;
222        }
223        let projection = self.projection_matrix_with(self.near_z(), false);
224        let coord = self.coordinate_point_matrix(&projection);
225        let from_center = coord * DMat4::from_translation(self.center_coordinate());
226        let (Some(inv_projection), Some(inverted_from_center)) = (projection.try_inverse(), from_center.try_inverse())
227        else {
228            return Matrices::ZERO;
229        };
230        let mut matrices = Matrices { projection, inv_projection, coord, inverted_from_center, ..Matrices::ZERO };
231        if self.is_globe() {
232            let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
233                Projection::world_size(self.params.scale),
234                self.center(WrapMode::Unwrapped).latitude(),
235            );
236            let globe_view_projection = VerticalPerspectiveProjection::globe_view_projection_matrix(self, globe_radius);
237            matrices.globe_view_projection = globe_view_projection;
238            matrices.inv_globe_view_projection = globe_view_projection.try_inverse().unwrap_or(DMat4::IDENTITY);
239            matrices.globe_clipping_plane = VerticalPerspectiveProjection::clipping_plane(self, globe_radius);
240            matrices.globe_camera_position = VerticalPerspectiveProjection::camera_position(self, globe_radius);
241        }
242        matrices
243    }
244
245    // MARK: - Dimensions
246
247    /// The size, in logical pixels.
248    #[must_use]
249    pub fn size(&self) -> Size {
250        self.params.size
251    }
252
253    /// Insets that move the vanishing point off the center of the view.
254    #[must_use]
255    pub(crate) fn frustum_offset(&self) -> EdgeInsets {
256        self.params.frustum_offset
257    }
258
259    /// Insets from the view's edges. The camera centers within the rest.
260    #[must_use]
261    pub(crate) fn padding(&self) -> EdgeInsets {
262        self.params.padding
263    }
264
265    #[must_use]
266    pub(crate) fn north_orientation(&self) -> NorthOrientation {
267        self.params.north_orientation
268    }
269
270    /// The rotation that the north orientation adds, in radians.
271    #[must_use]
272    pub(crate) fn north_orientation_angle(&self) -> f64 {
273        match self.params.north_orientation {
274            NorthOrientation::Upwards => 0.0,
275            NorthOrientation::Rightwards => PI / 2.0,
276            NorthOrientation::Downwards => PI,
277            NorthOrientation::Leftwards => -PI / 2.0,
278        }
279    }
280
281    /// Whether the map's center stands on its terrain
282    /// ([`Viewport::center_clamped_to_ground`]).
283    #[must_use]
284    pub(crate) fn center_clamped_to_ground(&self) -> bool {
285        self.params.center_clamped_to_ground
286    }
287
288    /// Whether drags and zooms on the globe turn the bearing
289    /// ([`Viewport::globe_free_bearing`]).
290    #[must_use]
291    pub(crate) fn globe_free_bearing(&self) -> bool {
292        self.params.globe_free_bearing
293    }
294
295    /// The center's offset from the middle of the view that the padding
296    /// makes, in pixels from the top left.
297    pub(crate) fn center_offset(&self) -> ScreenCoordinate {
298        let padding = &self.params.padding;
299        ScreenCoordinate::new(0.5 * (padding.left - padding.right), 0.5 * (padding.top - padding.bottom))
300    }
301
302    // MARK: - Camera
303
304    /// The center. `WrapMode::Unwrapped` keeps the copy of the world that
305    /// the camera is in.
306    #[must_use]
307    pub fn center(&self, wrap_mode: WrapMode) -> LatLng {
308        let world_size = Projection::world_size(self.params.scale);
309        LatLng::saturating(
310            mln_style::math::rad2deg(2.0 * (self.params.y / (world_size / M2PI)).exp().atan() - 0.5 * PI),
311            -self.params.x / (world_size / 360.0),
312            wrap_mode,
313        )
314    }
315
316    /// The world copy of `location` nearest the center, which bounds can keep
317    /// past the antimeridian.
318    #[must_use]
319    pub fn lat_lng_near_center(&self, location: &LatLng) -> LatLng {
320        let center = self.center(WrapMode::Unwrapped);
321        let wrapped_center = center.wrapped();
322        let mut nearest = location.wrapped();
323        nearest.unwrap_for_shortest_path(&wrapped_center);
324        LatLng::saturating(
325            nearest.latitude(),
326            nearest.longitude() + center.longitude() - wrapped_center.longitude(),
327            WrapMode::Unwrapped,
328        )
329    }
330
331    /// The center's altitude, in meters.
332    #[must_use]
333    pub fn center_altitude(&self) -> f64 {
334        self.params.center_altitude
335    }
336
337    /// Meters per pixel at the zoom, as at the center (GL JS's
338    /// `pixelsPerMeter`, inverted): the scale of every height the matrices
339    /// place, so that a point at the center's altitude draws at the center.
340    pub(crate) fn meters_per_pixel(&self) -> f64 {
341        Projection::meters_per_pixel_at_latitude(self.center(WrapMode::Unwrapped).latitude(), self.zoom())
342    }
343
344    /// The center's altitude in pixels at the zoom.
345    fn center_altitude_pixels(&self) -> f64 {
346        // A center at sea level, as on most maps, spares the conversion's
347        // transcendental functions on every new view.
348        if self.params.center_altitude == 0.0 {
349            return self.params.center_altitude;
350        }
351        self.params.center_altitude / self.meters_per_pixel()
352    }
353
354    #[must_use]
355    pub fn zoom(&self) -> f64 {
356        scale_zoom(self.params.scale)
357    }
358
359    /// The zoom, rounded down and clamped to the `u8` range.
360    #[must_use]
361    pub fn integer_zoom(&self) -> u8 {
362        f64::max(0.0, self.zoom()) as u8
363    }
364
365    /// The zoom's fractional part.
366    #[must_use]
367    #[cfg(test)]
368    pub(crate) fn zoom_fraction(&self) -> f64 {
369        self.zoom() - f64::from(self.integer_zoom())
370    }
371
372    /// 2 to the power of the zoom.
373    #[must_use]
374    pub(crate) fn scale(&self) -> f64 {
375        self.params.scale
376    }
377
378    /// The map's offset from the world's center along x, in pixels at the
379    /// scale: the negated center.
380    #[must_use]
381    pub(crate) fn x(&self) -> f64 {
382        self.params.x
383    }
384
385    /// The map's offset from the world's center along y.
386    #[must_use]
387    pub(crate) fn y(&self) -> f64 {
388        self.params.y
389    }
390
391    /// The map's rotation, counterclockwise: the negated bearing.
392    #[must_use]
393    pub fn angle(&self) -> f64 {
394        self.params.angle
395    }
396
397    /// The tilt toward the horizon. 0 looks straight down.
398    #[must_use]
399    pub fn pitch(&self) -> f64 {
400        self.params.pitch
401    }
402
403    #[must_use]
404    pub fn roll(&self) -> f64 {
405        self.params.roll
406    }
407
408    /// The vertical field of view.
409    #[must_use]
410    pub(crate) fn fov(&self) -> f64 {
411        self.params.fov
412    }
413
414    /// The field of view that the perspective projections use: [`fov`]
415    /// rounded to `f32`, the precision of the camera that drew the render
416    /// tests' expected images. At full precision, edges land a fraction of a
417    /// pixel away from theirs.
418    ///
419    /// [`fov`]: Self::fov
420    pub(crate) fn perspective_fov(&self) -> f64 {
421        f64::from(self.params.fov as f32)
422    }
423
424    /// The distance from the camera to the center, in pixels.
425    #[must_use]
426    pub fn camera_to_center_distance(&self) -> f64 {
427        0.5 * f64::from(self.params.size.height) / (self.params.fov / 2.0).tan()
428    }
429
430    /// GL JS's `getMercatorHorizon`: how far above the center of the view,
431    /// in pixels, the map ends and the sky starts. It is 0.85 of the way to
432    /// the flat map's geometric horizon, and never past 89.25 degrees from
433    /// straight down; at a pitch past that it is negative.
434    #[must_use]
435    pub(crate) fn mercator_horizon(&self) -> f64 {
436        let pitch = self.params.pitch;
437        self.camera_to_center_distance()
438            * f64::min((PI / 2.0 - pitch).tan() * 0.85, (max_mercator_horizon_angle() - pitch).tan())
439    }
440
441    #[must_use]
442    pub(crate) fn projection_mode(&self) -> ProjectionMode {
443        ProjectionMode {
444            axonometric: Some(AxonometricMode::from(self.params.axonometric)),
445            x_skew: Some(self.params.x_skew),
446            y_skew: Some(self.params.y_skew),
447        }
448    }
449
450    /// The camera, in degrees, as the map reports it.
451    #[must_use]
452    pub(crate) fn camera(&self) -> Camera {
453        Camera {
454            center: self.center(self.params.center_wrap),
455            center_altitude: self.center_altitude(),
456            padding: self.params.padding,
457            zoom: self.zoom(),
458            bearing: mln_style::math::rad2deg(-self.params.angle),
459            pitch: mln_style::math::rad2deg(self.params.pitch),
460            roll: mln_style::math::rad2deg(self.params.roll),
461            fov: mln_style::math::rad2deg(self.params.fov),
462        }
463    }
464
465    /// The view as its public description, at `scale_factor` physical pixels
466    /// in each logical pixel.
467    #[must_use]
468    pub fn map_view(&self, scale_factor: f64) -> MapView {
469        MapView {
470            camera: self.camera(),
471            extent: LogicalExtent { size: self.params.size, scale_factor },
472            projection_mode: self.projection_mode(),
473            viewport: Viewport {
474                north_orientation: self.params.north_orientation,
475                constrain_mode: self.params.constrain_mode,
476                center_clamped_to_ground: self.params.center_clamped_to_ground,
477                globe_free_bearing: self.params.globe_free_bearing,
478                frustum_offset: self.params.frustum_offset,
479            },
480            projection: self.params.projection_definition,
481        }
482    }
483
484    /// Whether the view shows anything: it has a size and a scale.
485    #[must_use]
486    pub(crate) fn is_valid(&self) -> bool {
487        !self.params.size.is_empty() && self.params.scale.is_finite() && self.params.scale > 0.0
488    }
489
490    /// The camera's position and orientation, or the default pose while the
491    /// view isn't valid.
492    pub(crate) fn camera_pose(&self) -> CameraPose {
493        if !self.is_valid() {
494            return CameraPose::default();
495        }
496        let world_size = Projection::world_size(self.params.scale);
497        // x and y are the map's position, the camera's negated, from the
498        // middle of the world.
499        let center = DVec3::new(
500            0.5 * world_size - self.params.x,
501            0.5 * world_size - self.params.y,
502            self.center_altitude_pixels(),
503        );
504        // Orient the camera, then move it back from the center along its line
505        // of sight.
506        let mut camera = CameraPose::from_angles(DVec3::ZERO, self.params.roll, self.params.pitch, self.params.angle);
507        camera.position = (center - camera.forward() * self.camera_to_center_distance()) / world_size;
508        camera
509    }
510
511    /// The camera's position and orientation.
512    #[must_use]
513    pub(crate) fn free_camera_options(&self) -> FreeCameraOptions {
514        let camera = self.camera_pose();
515        FreeCameraOptions { position: Some(camera.position), orientation: Some(camera.orientation) }
516    }
517
518    /// Where the camera's eye is: its Web Mercator point at zoom 0 (from 0
519    /// to 1 across, y south) and its altitude in meters, of the meters the
520    /// view places heights in ([`center_altitude`](Self::center_altitude)).
521    /// On the globe it is the point under the eye, in the world copy nearest
522    /// the center, with y past 0 or 1 over a polar cap, and the eye's height
523    /// above the sea-level sphere.
524    #[must_use]
525    pub(crate) fn eye_position(&self) -> DVec3 {
526        if self.is_globe() && self.is_valid() {
527            let eye = self.matrices.globe_camera_position;
528            return VerticalPerspectiveProjection::sphere_point_to_world(self, eye).unwrap_or(eye);
529        }
530        let position = self.camera_pose().position;
531        let world_size = Projection::world_size(self.params.scale);
532        DVec3::new(position.x, position.y, position.z * world_size * self.meters_per_pixel())
533    }
534
535    /// A 3 by 3 grid over the projection matrix's near plane, its corners,
536    /// the middles of its edges and its center, in the units of
537    /// [`eye_position`](Self::eye_position): the renderer drops what is
538    /// nearer, so ground above a point shows as a hole into it. On the globe
539    /// it is the globe matrix's near plane. All are the eye while the view
540    /// shows nothing.
541    #[must_use]
542    pub(crate) fn near_plane_points(&self) -> [DVec3; 9] {
543        let eye = self.eye_position();
544        if self.matrices.projection == DMat4::ZERO {
545            return [eye; 9];
546        }
547        let clip = |index: usize| DVec3::new((index % 3) as f64 - 1.0, (index / 3) as f64 - 1.0, -1.0);
548        if self.is_globe() {
549            let inverse = self.matrices.inv_globe_view_projection;
550            return std::array::from_fn(|index| {
551                let point = inverse.project_point3(clip(index));
552                VerticalPerspectiveProjection::sphere_point_to_world(self, point).unwrap_or(eye)
553            });
554        }
555        let world_size = Projection::world_size(self.params.scale);
556        std::array::from_fn(|index| {
557            let point = self.matrices.inv_projection.project_point3(clip(index));
558            DVec3::new(point.x / world_size, point.y / world_size, point.z)
559        })
560    }
561
562    // MARK: - Projection
563
564    /// 0 is Mercator, 1 is the globe, in between is the transition.
565    #[must_use]
566    pub(crate) fn projection_transition(&self) -> f64 {
567        self.params.projection_transition
568    }
569
570    /// Whether the view draws the globe, also while it hands over to or from
571    /// Mercator.
572    #[must_use]
573    pub fn is_globe(&self) -> bool {
574        self.params.projection_transition > 0.0
575    }
576
577    /// The globe while [`is_globe`](Self::is_globe), Mercator otherwise.
578    #[must_use]
579    pub fn projection(&self) -> crate::camera::Projection {
580        if self.is_globe() {
581            crate::camera::Projection::VerticalPerspective
582        } else {
583            crate::camera::Projection::Mercator
584        }
585    }
586
587    /// The same camera, size and center altitude on Mercator: the view at a
588    /// projection transition of 0. A view on Mercator is its own.
589    #[must_use]
590    pub(crate) fn mercator(&self) -> View {
591        if !self.is_globe() {
592            return self.clone();
593        }
594        View::new(ViewParams { projection_transition: 0.0, ..self.params })
595    }
596
597    /// The tile-to-world matrix of a tile at the view's scale.
598    #[must_use]
599    pub(crate) fn tile_matrix(&self, tile_id: &UnwrappedTileID) -> DMat4 {
600        mercator_tile_matrix(tile_id, self.params.scale)
601    }
602
603    /// The projection of a tile, through `proj_matrix`.
604    #[must_use]
605    pub(crate) fn projection_data_with(&self, tile_id: &UnwrappedTileID, proj_matrix: &DMat4) -> ProjectionData {
606        let mercator_matrix = *proj_matrix * self.tile_matrix(tile_id);
607        self.projection().projection_data(self, tile_id, &mercator_matrix)
608    }
609
610    /// The projection of a tile, through the projection matrix.
611    #[must_use]
612    pub fn projection_data(&self, tile_id: &UnwrappedTileID) -> ProjectionData {
613        self.projection_data_with(tile_id, &self.matrices.projection)
614    }
615
616    /// The projection of a tile whose Mercator tile-to-clip matrix is
617    /// `mercator_matrix`.
618    #[must_use]
619    pub(crate) fn projection_data_for_matrix(
620        &self,
621        tile_id: &UnwrappedTileID,
622        mercator_matrix: &DMat4,
623    ) -> ProjectionData {
624        self.projection().projection_data(self, tile_id, mercator_matrix)
625    }
626
627    /// The lowest ground near the center while terrain draws, in meters,
628    /// exaggerated; `None` without terrain
629    /// (`TransformState::set_terrain_min_elevation`).
630    #[must_use]
631    pub fn terrain_min_elevation(&self) -> Option<f64> {
632        self.params.terrain_min_elevation
633    }
634
635    /// The distance from the camera to the near plane of the projection
636    /// matrix, in pixels: 1, or a fiftieth of the view's height while
637    /// terrain draws, as in GL JS, for the depth precision raised ground
638    /// needs. The globe's matrix takes it while terrain draws too.
639    #[must_use]
640    pub(crate) fn near_z(&self) -> f64 {
641        match self.params.terrain_min_elevation {
642            Some(_) => f64::from(self.params.size.height) / 50.0,
643            None => 1.0,
644        }
645    }
646
647    /// GL JS's `cameraToSeaLevelDistance`, in pixels at the zoom: how far
648    /// the camera is from sea level along the view, past the center by its
649    /// altitude, at the pitch up to the horizon's limit, and at least half
650    /// the distance to the center.
651    #[must_use]
652    pub(crate) fn camera_to_sea_level_distance(&self) -> f64 {
653        let camera_to_center_distance = self.camera_to_center_distance();
654        let limited_pitch = self.params.pitch.min(max_mercator_horizon_angle());
655        f64::max(
656            camera_to_center_distance / 2.0,
657            camera_to_center_distance + self.center_altitude_pixels() / limited_pitch.cos(),
658        )
659    }
660
661    /// The distance from the camera to the far plane of the projection
662    /// matrix, in pixels at the zoom, as GL JS's
663    /// [`calculateNearFarZ`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/camera/mercator_camera_math.ts#L191-L230)
664    /// places it: where the top of the view or the horizon, whichever is nearer,
665    /// meets the plane of the lowest of the center, the ground and 100 m
666    /// below the camera. The ground is sea level, or the terrain's lowest
667    /// ground while terrain draws. The frustum offset shortens it.
668    #[must_use]
669    pub(crate) fn far_z(&self) -> f64 {
670        let params = &self.params;
671        let camera_to_center_distance = self.camera_to_center_distance();
672        let pixels_per_meter = 1.0 / self.meters_per_pixel();
673
674        // Heights in pixels at the zoom.
675        let ground = params.terrain_min_elevation.unwrap_or(0.0) * pixels_per_meter;
676        let center_altitude = self.center_altitude_pixels();
677        let limited_pitch = params.pitch.min(max_mercator_horizon_angle());
678        let camera_to_sea_level_distance = self.camera_to_sea_level_distance();
679        let camera_altitude = params.pitch.cos() * camera_to_center_distance + center_altitude;
680        let lowest = center_altitude.min(ground).min(camera_altitude - 100.0 * pixels_per_meter);
681        let lowest_plane = if lowest < 0.0 {
682            camera_to_sea_level_distance - lowest / limited_pitch.cos()
683        } else {
684            camera_to_sea_level_distance
685        };
686
687        // How far past the center, along the lowest plane, the ray at `angle`
688        // above the center of the view meets it: the law of sines in the
689        // triangle of the camera, the center and that point.
690        let ground_angle = PI / 2.0 + params.pitch;
691        let distance_past_center = |angle: f64| {
692            angle.sin() * lowest_plane / mln_style::math::clamp_f64(PI - ground_angle - angle, 0.01, PI - 0.01).sin()
693        };
694        let top_half_distance = distance_past_center(self.tan_fov_above_center().atan())
695            .min(distance_past_center(self.fov_center_to_horizon()));
696
697        (limited_pitch.sin() * top_half_distance + lowest_plane) * 1.01
698    }
699
700    /// Whether a flat map ends inside the view: its edge farthest up the map
701    /// reaches past the horizon, where the sky starts.
702    #[must_use]
703    pub(crate) fn shows_horizon(&self) -> bool {
704        self.fov_center_to_horizon() < self.tan_fov_above_center().atan()
705    }
706
707    /// The tangent of the angle from the center of the view, with the
708    /// padding, to its edge farthest up the map, in units where 1 is a pixel
709    /// at the center of the map: to the top edge of an upright view, and to
710    /// its farthest corner as the view turns.
711    fn tan_fov_above_center(&self) -> f64 {
712        let params = &self.params;
713        let half_width = 0.5 * f64::from(params.size.width);
714        let half_height = 0.5 * f64::from(params.size.height);
715        let offset = self.center_offset();
716        // The view's reach from its padded center to each edge, in pixels.
717        let (left, right) = (half_width + offset.x, half_width - offset.x);
718        let (top, bottom) = (half_height + offset.y - params.frustum_offset.top, half_height - offset.y);
719        let up = self.up_the_map();
720        let reach = (up.x * right).max(-up.x * left) + (up.y * top).max(-up.y * bottom);
721        reach / half_height * (params.fov / 2.0).tan()
722    }
723
724    /// The angle from the center of the view, with the padding, up the map
725    /// to the horizon, where the map ends and the sky starts (GL JS's
726    /// `calculateNearFarZ`): at high pitch it is below the top of the view.
727    /// The sky draws the horizon [`mercator_horizon`](Self::mercator_horizon)
728    /// pixels up the map from the center of the view without the padding,
729    /// so the padding's offset up the map moves it, but never past 89.25
730    /// degrees from straight down, nor below the center.
731    fn fov_center_to_horizon(&self) -> f64 {
732        let camera_to_center = self.camera_to_center_distance();
733        let horizon = self.mercator_horizon();
734        let min_horizon_angle = PI / 2.0 - max_mercator_horizon_angle();
735        if (horizon / camera_to_center).atan() <= min_horizon_angle {
736            return min_horizon_angle;
737        }
738        let offset = self.center_offset();
739        let offset_up = DVec2::new(-offset.x, offset.y).dot(self.up_the_map());
740        let farthest = camera_to_center * (max_mercator_horizon_angle() - self.params.pitch).tan();
741        (mln_style::math::clamp_f64(horizon + offset_up, 0.0, farthest) / camera_to_center).atan()
742    }
743
744    /// The unit direction up the map in the view, x right and y up, which
745    /// the roll and the north orientation turn: a roll of 90 degrees turns
746    /// the left edge up.
747    fn up_the_map(&self) -> DVec2 {
748        let (sin, cos) = self.params.roll.sin_cos();
749        DVec2::from_angle(-self.north_orientation_angle()).rotate(DVec2::new(-sin, cos))
750    }
751
752    /// The projection matrix with its near plane at `near_z` pixels, aligned
753    /// to the pixel grid if `aligned`; zero while the size is empty.
754    #[must_use]
755    pub(crate) fn projection_matrix_with(&self, near_z: f64, aligned: bool) -> DMat4 {
756        let params = &self.params;
757        if params.size.is_empty() {
758            return DMat4::ZERO;
759        }
760
761        let offset = self.center_offset();
762        let width = f64::from(params.size.width);
763        let height = f64::from(params.size.height);
764
765        let camera = self.camera_pose();
766        let pixels_per_meter = 1.0 / self.meters_per_pixel();
767        let world_to_camera = camera.world_to_camera(params.scale, pixels_per_meter);
768        let mut camera_to_clip = perspective(self.perspective_fov(), width / height, near_z, self.far_z());
769
770        // The vanishing point moves to the center of the padded view, from -1
771        // to 1 across it. An axonometric view has none.
772        if !params.axonometric {
773            camera_to_clip.z_axis.x = -offset.x * 2.0 / width;
774            camera_to_clip.z_axis.y = offset.y * 2.0 / height;
775        }
776
777        if params.north_orientation != NorthOrientation::Upwards {
778            camera_to_clip *= DMat4::from_rotation_z(-self.north_orientation_angle());
779        }
780
781        let mut proj_matrix = camera_to_clip * world_to_camera;
782
783        if params.axonometric {
784            // Without perspective, z skews x and y instead.
785            proj_matrix.z_axis.w = 0.0;
786            proj_matrix.z_axis.x = params.x_skew * pixels_per_meter;
787            proj_matrix.z_axis.y = params.y_skew * pixels_per_meter;
788        }
789
790        // The pixel-aligned matrix, for raster tiles: the center moves to a
791        // whole pixel, and by half a pixel more along a side of odd length,
792        // with the shift turned by the bearing and kept within half a pixel,
793        // so that rasters at right angles draw crisp.
794        if aligned {
795            let world_size = Projection::world_size(params.scale);
796            let dx = params.x - 0.5 * world_size;
797            let dy = params.y - 0.5 * world_size;
798
799            let x_shift = f64::from(params.size.width % 2) / 2.0;
800            let y_shift = f64::from(params.size.height % 2) / 2.0;
801            let angle_cos = params.angle.cos();
802            let angle_sin = params.angle.sin();
803            let dxa = -modf_fraction(dx) + angle_cos * x_shift + angle_sin * y_shift;
804            let dya = -modf_fraction(dy) + angle_cos * y_shift + angle_sin * x_shift;
805            proj_matrix *= DMat4::from_translation(DVec3::new(
806                if dxa > 0.5 { dxa - 1.0 } else { dxa },
807                if dya > 0.5 { dya - 1.0 } else { dya },
808                0.0,
809            ));
810        }
811        proj_matrix
812    }
813
814    /// The projection matrix: from world pixels at the scale, z in meters, to
815    /// clip space.
816    #[cfg(any(test, feature = "bench"))]
817    #[must_use]
818    pub(crate) fn projection_matrix(&self) -> DMat4 {
819        self.matrices.projection
820    }
821
822    #[must_use]
823    pub(crate) fn inverse_projection_matrix(&self) -> DMat4 {
824        self.matrices.inv_projection
825    }
826
827    /// The globe's view projection, from unit-sphere space to clip space,
828    /// while [`is_globe`](Self::is_globe).
829    #[must_use]
830    pub(crate) fn globe_view_projection_matrix(&self) -> DMat4 {
831        self.matrices.globe_view_projection
832    }
833
834    #[must_use]
835    pub(crate) fn inverse_globe_view_projection_matrix(&self) -> DMat4 {
836        self.matrices.inv_globe_view_projection
837    }
838
839    /// The plane, as `ax + by + cz + d`, that separates the globe's visible
840    /// hemisphere from its back.
841    #[must_use]
842    pub(crate) fn globe_clipping_plane(&self) -> DVec4 {
843        self.matrices.globe_clipping_plane
844    }
845
846    /// The camera in unit-sphere space.
847    #[must_use]
848    pub fn globe_camera_position(&self) -> DVec3 {
849        self.matrices.globe_camera_position
850    }
851
852    /// The center of the map in the units that `coord` takes: world pixels
853    /// over the tile size, at the scale.
854    fn center_coordinate(&self) -> DVec3 {
855        let world_size = Projection::world_size(self.params.scale);
856        DVec3::new(
857            (0.5 * world_size - self.params.x) / TILE_SIZE_D,
858            (0.5 * world_size - self.params.y) / TILE_SIZE_D,
859            0.0,
860        )
861    }
862
863    /// The matrix from world space in tiles to screen pixels, y up.
864    fn coordinate_point_matrix(&self, proj_matrix: &DMat4) -> DMat4 {
865        let size = self.params.size;
866        let pixel_matrix =
867            DMat4::from_scale(DVec3::new(f64::from(size.width) / 2.0, -f64::from(size.height) / 2.0, 1.0))
868                * DMat4::from_translation(DVec3::new(1.0, -1.0, 0.0));
869        pixel_matrix * *proj_matrix * DMat4::from_scale(DVec3::new(TILE_SIZE_D, TILE_SIZE_D, 1.0))
870    }
871
872    // MARK: - Conversions
873
874    /// The screen point of a location, measured from the bottom edge (y up).
875    #[must_use]
876    pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
877        self.lat_lng_to_screen_coordinate_at(lat_lng, 0.0)
878    }
879
880    /// The screen point of a location `height` meters above sea level,
881    /// measured from the bottom edge (y up). The globe raises it along its
882    /// vertical.
883    #[must_use]
884    pub(crate) fn lat_lng_to_screen_coordinate_at(&self, lat_lng: &LatLng, height: f64) -> ScreenCoordinate {
885        self.clip_point_at(lat_lng, height).0
886    }
887
888    /// The screen point of a location and its clip-space position, whose w
889    /// is negative behind the camera. Both are zero while the size is empty.
890    #[must_use]
891    #[cfg(test)]
892    pub(crate) fn lat_lng_to_screen_coordinate_with_clip(&self, lat_lng: &LatLng) -> (ScreenCoordinate, DVec4) {
893        self.clip_point_at(lat_lng, 0.0)
894    }
895
896    /// [`lat_lng_to_screen_coordinate_with_clip`] of a location `height`
897    /// meters above sea level.
898    ///
899    /// [`lat_lng_to_screen_coordinate_with_clip`]: Self::lat_lng_to_screen_coordinate_with_clip
900    fn clip_point_at(&self, lat_lng: &LatLng, height: f64) -> (ScreenCoordinate, DVec4) {
901        if self.params.size.is_empty() {
902            return (ScreenCoordinate::new(0.0, 0.0), DVec4::ZERO);
903        }
904
905        if self.is_globe() {
906            return VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(self, lat_lng, height);
907        }
908
909        let pt = Projection::project(lat_lng, self.params.scale);
910        let p = self.matrices.coord * DVec4::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D, height, 1.0);
911        (ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w), p)
912    }
913
914    /// Whether the globe hides a location from the camera; a Mercator view
915    /// hides nothing.
916    #[must_use]
917    pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
918        if self.params.size.is_empty() || !self.is_globe() {
919            return false;
920        }
921        let surface = VerticalPerspectiveProjection::surface_vector(lat_lng);
922        self.globe_clipping_plane().dot(surface.extend(1.0)) < 0.0
923    }
924
925    /// The tile coordinate under a screen point (y up) at `at_zoom`, as GL
926    /// JS's `pointCoordinate`.
927    #[must_use]
928    pub(crate) fn screen_coordinate_to_tile_coordinate(&self, point: &ScreenCoordinate, at_zoom: u8) -> TileCoordinate {
929        if self.params.size.is_empty() {
930            return TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 };
931        }
932
933        if self.is_globe() {
934            return match VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(
935                self,
936                point,
937                0.0,
938                WrapMode::Unwrapped,
939            ) {
940                Some(lat_lng) => TileCoordinate::from_lat_lng(f64::from(at_zoom), &lat_lng),
941                None => TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 },
942            };
943        }
944
945        self.mercator_screen_coordinate_to_tile_coordinate(point, at_zoom, 0.0)
946    }
947
948    /// The tile coordinate at `at_zoom` where the line of sight through
949    /// `point` (y up) meets the plane `height` meters above sea level; where
950    /// the line doesn't descend, the point at clip depth 0.
951    fn mercator_screen_coordinate_to_tile_coordinate(
952        &self,
953        point: &ScreenCoordinate,
954        at_zoom: u8,
955        height: f64,
956    ) -> TileCoordinate {
957        let flipped_y = f64::from(self.params.size.height) - point.y;
958
959        // The point's depth isn't known: unproject it at two depths, and take
960        // where the line between them meets the plane.
961        let inverted = self.matrices.inverted_from_center;
962        let offset0 = inverted.project_point3(DVec3::new(point.x, flipped_y, 0.0));
963        let offset1 = inverted.project_point3(DVec3::new(point.x, flipped_y, 1.0));
964
965        let z0 = offset0.z;
966        let z1 = offset1.z;
967        // `z0 - 0.0` is `z0`, so sea level is the flat map's plane to the bit.
968        let t = if z0 <= z1 { 0.0 } else { -(z0 - height) / (z1 - z0) };
969
970        let offset = offset0 + (offset1 - offset0) * t;
971        let center = self.center_coordinate();
972        let factor = f64::from(1i32.wrapping_shl(u32::from(at_zoom)));
973        let scale = self.params.scale;
974        TileCoordinate {
975            p: Point::new((center.x + offset.x) / scale * factor, (center.y + offset.y) / scale * factor),
976            z: f64::from(at_zoom),
977        }
978    }
979
980    /// The location under `point`, measured from the bottom edge (y up).
981    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
982    /// NaN or infinite point.
983    pub(crate) fn screen_coordinate_to_lat_lng(
984        &self,
985        point: &ScreenCoordinate,
986        wrap_mode: WrapMode,
987    ) -> Result<LatLng, Error> {
988        self.screen_coordinate_to_lat_lng_at(point, 0.0, wrap_mode)
989    }
990
991    /// The location where the line of sight through `point`, measured from
992    /// the bottom edge (y up), meets the plane `height` meters above sea
993    /// level; where the line doesn't descend, as at sea level, the point it
994    /// passes a little way from the camera. The globe meets the sphere
995    /// `height` meters above sea level, and a line that misses it the
996    /// nearest point of that sphere's horizon. Fails as
997    /// `screen_coordinate_to_lat_lng`.
998    pub fn screen_coordinate_to_lat_lng_at(
999        &self,
1000        point: &ScreenCoordinate,
1001        height: f64,
1002        wrap_mode: WrapMode,
1003    ) -> Result<LatLng, Error> {
1004        // Without a size the point is Mercator's, as the tile coordinate is.
1005        if self.is_globe() && !self.params.size.is_empty() {
1006            if point.x.is_nan() || point.y.is_nan() {
1007                return Err(Error::invalid_argument("screen coordinate must not be NaN"));
1008            }
1009            if !point.x.is_finite() || !point.y.is_finite() {
1010                return Err(Error::invalid_argument("screen coordinate must not be infinite"));
1011            }
1012            return VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(self, point, height, wrap_mode)
1013                .ok_or_else(|| Error::invalid_argument("the camera shows no location"));
1014        }
1015        let coord = if self.params.size.is_empty() {
1016            self.screen_coordinate_to_tile_coordinate(point, 0)
1017        } else {
1018            self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height)
1019        };
1020        Projection::unproject(&coord.p, 1.0 / TILE_SIZE_D, wrap_mode)
1021    }
1022
1023    /// The line of sight through `point`, measured from the bottom edge (y
1024    /// up), from the near plane to the far plane: each end's Web Mercator
1025    /// point at zoom 0 (x in the world copy the view shows it in) and its
1026    /// height in meters. `None` on the globe, while the view shows nothing,
1027    /// and for a point that isn't finite.
1028    #[must_use]
1029    pub fn line_of_sight(&self, point: &ScreenCoordinate) -> Option<(DVec3, DVec3)> {
1030        if self.is_globe() || self.matrices.projection == DMat4::ZERO {
1031            return None;
1032        }
1033        let flipped_y = f64::from(self.params.size.height) - point.y;
1034        // The matrices are OpenGL's: clip depth runs from -1 at the near plane
1035        // to 1 at the far plane.
1036        let inverted = self.matrices.inverted_from_center;
1037        let center = self.center_coordinate();
1038        let scale = self.params.scale;
1039        let world = |depth: f64| {
1040            let offset = inverted.project_point3(DVec3::new(point.x, flipped_y, depth));
1041            DVec3::new((center.x + offset.x) / scale, (center.y + offset.y) / scale, offset.z)
1042        };
1043        let (near, far) = (world(-1.0), world(1.0));
1044        (near.is_finite() && far.is_finite()).then_some((near, far))
1045    }
1046
1047    /// How much farther the bottom-left corner of the view is from the
1048    /// camera than the center, by which queries pad what they look for; 0
1049    /// while the size is empty.
1050    #[must_use]
1051    pub(crate) fn max_pitch_scale_factor(&self) -> f64 {
1052        if self.params.size.is_empty() {
1053            return 0.0;
1054        }
1055        // The globe pads queries with the Mercator factor, as GL JS does, from
1056        // the corner's unclamped Mercator position.
1057        let corner = self.mercator_screen_coordinate_to_tile_coordinate(
1058            &ScreenCoordinate::new(0.0, f64::from(self.params.size.height)),
1059            0,
1060            0.0,
1061        );
1062        // A point on the screen has a LatLng unless the view holds NaN.
1063        let Ok(lat_lng) = Projection::unproject(&corner.p, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped) else {
1064            return 0.0;
1065        };
1066
1067        let scale = self.params.scale;
1068        let pt = if self.is_globe() {
1069            Point::new(corner.p.x * scale, corner.p.y * scale)
1070        } else {
1071            let pt = Projection::project(&lat_lng, scale);
1072            Point::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D)
1073        };
1074        let top_point = self.matrices.coord * DVec4::new(pt.x, pt.y, 0.0, 1.0);
1075        top_point.w / self.camera_to_center_distance()
1076    }
1077}