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