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