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