1use std::f64::consts::PI;
5
6use geometry::Point;
7use glam::dcamera::rh::proj::opengl::perspective;
8use glam::{DMat4, DVec2, DVec3, DVec4};
9use mln_style::constants::TILE_SIZE_D;
10use mln_style::error::Error;
11use mln_style::geo::{LatLng, WrapMode};
12use mln_style::size::Size;
13use mln_style::types::ProjectionDefinition;
14
15use crate::camera::camera::FreeCameraOptions;
16use crate::camera::camera_pose::CameraPose;
17use crate::camera::constants::DEFAULT_FOV;
18use crate::camera::map_view::{Camera, LogicalExtent, MapView, Viewport};
19use crate::camera::mode::{ConstrainMode, ViewportMode};
20use crate::camera::projection::{ProjectionData, mercator_tile_matrix};
21use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
22use crate::camera::tile_coordinate::TileCoordinate;
23use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
24pub use crate::geo::NorthOrientation;
25use crate::geo::constants::M2PI;
26use crate::geo::projection::Projection;
27use crate::geo::{EdgeInsets, ScreenCoordinate};
28use crate::tile::UnwrappedTileID;
29
30pub(crate) fn max_mercator_horizon_angle() -> f64 {
34 mln_style::math::deg2rad(89.25)
35}
36
37fn 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#[must_use]
47pub fn zoom_scale(zoom: f64) -> f64 {
48 round_for_accuracy(2.0f64.powf(zoom))
49}
50
51#[must_use]
53pub fn scale_zoom(scale: f64) -> f64 {
54 round_for_accuracy(scale.log2())
55}
56
57pub(crate) fn map_offset(center: &LatLng, scale: f64, globe: bool) -> (f64, f64) {
61 let world_size = Projection::world_size(scale);
62 let latitude = mln_style::math::deg2rad(center.latitude());
63 let m = 1.0 - 1e-15;
64 let f = mln_style::math::clamp_f64(latitude.sin(), -m, m);
65 let x = -center.longitude() * (world_size / 360.0);
66 let cc = world_size / M2PI;
67 let y = if globe { cc * latitude.tan().asinh() } else { 0.5 * cc * ((1.0 + f) / (1.0 - f)).ln() };
68 (x, y)
69}
70
71fn 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#[derive(Clone, Copy, Debug, PartialEq)]
81pub(crate) struct ViewParams {
82 pub(crate) size: Size,
83 pub(crate) frustum_offset: EdgeInsets,
84 pub(crate) north_orientation: NorthOrientation,
85 pub(crate) viewport_mode: ViewportMode,
86 pub(crate) constrain_mode: ConstrainMode,
89 pub(crate) center_clamped_to_ground: bool,
92 pub(crate) globe_free_bearing: bool,
95 pub(crate) projection_definition: ProjectionDefinition,
97 pub(crate) projection_transition: f64,
99 pub(crate) padding: EdgeInsets,
100 pub(crate) x: f64,
103 pub(crate) y: f64,
104 pub(crate) center_altitude: f64,
107 pub(crate) scale: f64,
108 pub(crate) angle: f64,
111 pub(crate) pitch: f64,
112 pub(crate) roll: f64,
113 pub(crate) fov: f64,
114 pub(crate) x_skew: f64,
115 pub(crate) y_skew: f64,
116 pub(crate) axonometric: bool,
117 pub(crate) center_wrap: WrapMode,
119 pub(crate) terrain_min_elevation: Option<f64>,
122}
123
124impl ViewParams {
125 pub(crate) fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
126 ViewParams {
127 size: Size::default(),
128 frustum_offset: EdgeInsets::default(),
129 north_orientation: NorthOrientation::Upwards,
130 viewport_mode,
131 constrain_mode,
132 center_clamped_to_ground: true,
133 globe_free_bearing: false,
134 projection_definition: ProjectionDefinition::default(),
135 projection_transition: 0.0,
136 padding: EdgeInsets::default(),
137 x: 0.0,
138 y: 0.0,
139 center_altitude: 0.0,
140 scale: 1.0,
141 angle: 0.0,
142 pitch: 0.0,
143 roll: 0.0,
144 fov: DEFAULT_FOV,
145 x_skew: 0.0,
146 y_skew: 1.0,
147 axonometric: false,
148 center_wrap: WrapMode::Unwrapped,
149 terrain_min_elevation: None,
150 }
151 }
152}
153
154#[derive(Clone, Copy, Debug)]
157struct Matrices {
158 projection: DMat4,
159 inv_projection: DMat4,
160 coord: DMat4,
161 inverted_from_center: DMat4,
165 globe_view_projection: DMat4,
166 inv_globe_view_projection: DMat4,
167 globe_clipping_plane: DVec4,
168 globe_camera_position: DVec3,
169}
170
171impl Matrices {
172 const ZERO: Matrices = Matrices {
173 projection: DMat4::ZERO,
174 inv_projection: DMat4::ZERO,
175 coord: DMat4::ZERO,
176 inverted_from_center: DMat4::ZERO,
177 globe_view_projection: DMat4::ZERO,
178 inv_globe_view_projection: DMat4::ZERO,
179 globe_clipping_plane: DVec4::ZERO,
180 globe_camera_position: DVec3::ZERO,
181 };
182}
183
184#[derive(Clone, Debug)]
191pub struct View {
192 params: ViewParams,
193 matrices: Matrices,
194}
195
196impl PartialEq for View {
197 fn eq(&self, other: &Self) -> bool {
199 self.params == other.params
200 }
201}
202
203impl Default for View {
204 fn default() -> Self {
205 View::new(ViewParams::new(ConstrainMode::HeightOnly, ViewportMode::Default))
206 }
207}
208
209impl View {
210 pub(crate) fn new(params: ViewParams) -> Self {
211 let mut view = View { params, matrices: Matrices::ZERO };
212 view.matrices = view.compute_matrices();
213 view
214 }
215
216 pub(crate) fn params(&self) -> &ViewParams {
217 &self.params
218 }
219
220 fn compute_matrices(&self) -> Matrices {
222 if self.params.size.is_empty() {
223 return Matrices::ZERO;
224 }
225 let projection = self.projection_matrix_with(self.near_z(), false);
226 let coord = self.coordinate_point_matrix(&projection);
227 let from_center = coord * DMat4::from_translation(self.center_coordinate());
228 let (Some(inv_projection), Some(inverted_from_center)) = (projection.try_inverse(), from_center.try_inverse())
229 else {
230 return Matrices::ZERO;
231 };
232 let mut matrices = Matrices { projection, inv_projection, coord, inverted_from_center, ..Matrices::ZERO };
233 if self.is_globe() {
234 let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
235 Projection::world_size(self.params.scale),
236 self.center(WrapMode::Unwrapped).latitude(),
237 );
238 let globe_view_projection = VerticalPerspectiveProjection::globe_view_projection_matrix(self, globe_radius);
239 matrices.globe_view_projection = globe_view_projection;
240 matrices.inv_globe_view_projection = globe_view_projection.try_inverse().unwrap_or(DMat4::IDENTITY);
241 matrices.globe_clipping_plane = VerticalPerspectiveProjection::clipping_plane(self, globe_radius);
242 matrices.globe_camera_position = VerticalPerspectiveProjection::camera_position(self, globe_radius);
243 }
244 matrices
245 }
246
247 #[must_use]
251 pub fn size(&self) -> Size {
252 self.params.size
253 }
254
255 #[must_use]
257 pub fn frustum_offset(&self) -> EdgeInsets {
258 self.params.frustum_offset
259 }
260
261 #[must_use]
263 pub fn padding(&self) -> EdgeInsets {
264 self.params.padding
265 }
266
267 #[must_use]
268 pub fn north_orientation(&self) -> NorthOrientation {
269 self.params.north_orientation
270 }
271
272 #[must_use]
274 pub fn north_orientation_angle(&self) -> f64 {
275 match self.params.north_orientation {
276 NorthOrientation::Upwards => 0.0,
277 NorthOrientation::Rightwards => PI / 2.0,
278 NorthOrientation::Downwards => PI,
279 NorthOrientation::Leftwards => -PI / 2.0,
280 }
281 }
282
283 #[must_use]
284 pub fn viewport_mode(&self) -> ViewportMode {
285 self.params.viewport_mode
286 }
287
288 #[must_use]
291 pub fn center_clamped_to_ground(&self) -> bool {
292 self.params.center_clamped_to_ground
293 }
294
295 #[must_use]
298 pub fn globe_free_bearing(&self) -> bool {
299 self.params.globe_free_bearing
300 }
301
302 pub(crate) fn center_offset(&self) -> ScreenCoordinate {
305 let padding = &self.params.padding;
306 ScreenCoordinate::new(0.5 * (padding.left - padding.right), 0.5 * (padding.top - padding.bottom))
307 }
308
309 #[must_use]
314 pub fn center(&self, wrap_mode: WrapMode) -> LatLng {
315 let world_size = Projection::world_size(self.params.scale);
316 LatLng::saturating(
317 mln_style::math::rad2deg(2.0 * (self.params.y / (world_size / M2PI)).exp().atan() - 0.5 * PI),
318 -self.params.x / (world_size / 360.0),
319 wrap_mode,
320 )
321 }
322
323 #[must_use]
326 pub fn lat_lng_near_center(&self, location: &LatLng) -> LatLng {
327 let center = self.center(WrapMode::Unwrapped);
328 let wrapped_center = center.wrapped();
329 let mut nearest = location.wrapped();
330 nearest.unwrap_for_shortest_path(&wrapped_center);
331 LatLng::saturating(
332 nearest.latitude(),
333 nearest.longitude() + center.longitude() - wrapped_center.longitude(),
334 WrapMode::Unwrapped,
335 )
336 }
337
338 #[must_use]
340 pub fn center_altitude(&self) -> f64 {
341 self.params.center_altitude
342 }
343
344 pub(crate) fn meters_per_pixel(&self) -> f64 {
348 Projection::meters_per_pixel_at_latitude(self.center(WrapMode::Unwrapped).latitude(), self.zoom())
349 }
350
351 fn center_altitude_pixels(&self) -> f64 {
353 if self.params.center_altitude == 0.0 {
356 return self.params.center_altitude;
357 }
358 self.params.center_altitude / self.meters_per_pixel()
359 }
360
361 #[must_use]
362 pub fn zoom(&self) -> f64 {
363 scale_zoom(self.params.scale)
364 }
365
366 #[must_use]
368 pub fn integer_zoom(&self) -> u8 {
369 f64::max(0.0, self.zoom()) as u8
370 }
371
372 #[must_use]
374 pub fn zoom_fraction(&self) -> f64 {
375 self.zoom() - f64::from(self.integer_zoom())
376 }
377
378 #[must_use]
380 pub fn scale(&self) -> f64 {
381 self.params.scale
382 }
383
384 #[must_use]
387 pub fn x(&self) -> f64 {
388 self.params.x
389 }
390
391 #[must_use]
393 pub fn y(&self) -> f64 {
394 self.params.y
395 }
396
397 #[must_use]
399 pub fn angle(&self) -> f64 {
400 self.params.angle
401 }
402
403 #[must_use]
405 pub fn pitch(&self) -> f64 {
406 self.params.pitch
407 }
408
409 #[must_use]
410 pub fn roll(&self) -> f64 {
411 self.params.roll
412 }
413
414 #[must_use]
416 pub fn fov(&self) -> f64 {
417 self.params.fov
418 }
419
420 pub(crate) fn perspective_fov(&self) -> f64 {
427 f64::from(self.params.fov as f32)
428 }
429
430 #[must_use]
432 pub fn camera_to_center_distance(&self) -> f64 {
433 0.5 * f64::from(self.params.size.height) / (self.params.fov / 2.0).tan()
434 }
435
436 #[must_use]
441 pub fn mercator_horizon(&self) -> f64 {
442 let pitch = self.params.pitch;
443 self.camera_to_center_distance()
444 * f64::min((PI / 2.0 - pitch).tan() * 0.85, (max_mercator_horizon_angle() - pitch).tan())
445 }
446
447 #[must_use]
448 pub fn projection_mode(&self) -> ProjectionMode {
449 ProjectionMode {
450 axonometric: Some(AxonometricMode::from(self.params.axonometric)),
451 x_skew: Some(self.params.x_skew),
452 y_skew: Some(self.params.y_skew),
453 }
454 }
455
456 #[must_use]
458 pub fn camera(&self) -> Camera {
459 Camera {
460 center: self.center(self.params.center_wrap),
461 center_altitude: self.center_altitude(),
462 padding: self.params.padding,
463 zoom: self.zoom(),
464 bearing: mln_style::math::rad2deg(-self.params.angle),
465 pitch: mln_style::math::rad2deg(self.params.pitch),
466 roll: mln_style::math::rad2deg(self.params.roll),
467 fov: mln_style::math::rad2deg(self.params.fov),
468 }
469 }
470
471 #[must_use]
474 pub fn map_view(&self, scale_factor: f64) -> MapView {
475 MapView {
476 camera: self.camera(),
477 extent: LogicalExtent { size: self.params.size, scale_factor },
478 projection_mode: self.projection_mode(),
479 viewport: Viewport {
480 north_orientation: self.params.north_orientation,
481 constrain_mode: self.params.constrain_mode,
482 viewport_mode: self.params.viewport_mode,
483 center_clamped_to_ground: self.params.center_clamped_to_ground,
484 globe_free_bearing: self.params.globe_free_bearing,
485 frustum_offset: self.params.frustum_offset,
486 },
487 projection: self.params.projection_definition,
488 }
489 }
490
491 #[must_use]
493 pub fn is_valid(&self) -> bool {
494 !self.params.size.is_empty() && self.params.scale.is_finite() && self.params.scale > 0.0
495 }
496
497 pub(crate) fn camera_pose(&self) -> CameraPose {
500 if !self.is_valid() {
501 return CameraPose::default();
502 }
503 let world_size = Projection::world_size(self.params.scale);
504 let center = DVec3::new(
507 0.5 * world_size - self.params.x,
508 0.5 * world_size - self.params.y,
509 self.center_altitude_pixels(),
510 );
511 let mut camera = CameraPose::from_angles(DVec3::ZERO, self.params.roll, self.params.pitch, self.params.angle);
514 camera.position = (center - camera.forward() * self.camera_to_center_distance()) / world_size;
515 camera
516 }
517
518 #[must_use]
520 pub fn free_camera_options(&self) -> FreeCameraOptions {
521 let camera = self.camera_pose();
522 FreeCameraOptions { position: Some(camera.position), orientation: Some(camera.orientation) }
523 }
524
525 #[must_use]
532 pub fn eye_position(&self) -> DVec3 {
533 if self.is_globe() && self.is_valid() {
534 let eye = self.matrices.globe_camera_position;
535 return VerticalPerspectiveProjection::sphere_point_to_world(self, eye).unwrap_or(eye);
536 }
537 let position = self.camera_pose().position;
538 let world_size = Projection::world_size(self.params.scale);
539 DVec3::new(position.x, position.y, position.z * world_size * self.meters_per_pixel())
540 }
541
542 #[must_use]
549 pub fn near_plane_points(&self) -> [DVec3; 9] {
550 let eye = self.eye_position();
551 if self.matrices.projection == DMat4::ZERO {
552 return [eye; 9];
553 }
554 let clip = |index: usize| DVec3::new((index % 3) as f64 - 1.0, (index / 3) as f64 - 1.0, -1.0);
555 if self.is_globe() {
556 let inverse = self.matrices.inv_globe_view_projection;
557 return std::array::from_fn(|index| {
558 let point = inverse.project_point3(clip(index));
559 VerticalPerspectiveProjection::sphere_point_to_world(self, point).unwrap_or(eye)
560 });
561 }
562 let world_size = Projection::world_size(self.params.scale);
563 std::array::from_fn(|index| {
564 let point = self.matrices.inv_projection.project_point3(clip(index));
565 DVec3::new(point.x / world_size, point.y / world_size, point.z)
566 })
567 }
568
569 #[must_use]
572 pub fn projection_definition(&self) -> ProjectionDefinition {
573 self.params.projection_definition
574 }
575
576 #[must_use]
578 pub fn projection_transition(&self) -> f64 {
579 self.params.projection_transition
580 }
581
582 #[must_use]
585 pub fn is_globe(&self) -> bool {
586 self.params.projection_transition > 0.0
587 }
588
589 #[must_use]
591 pub fn projection(&self) -> crate::camera::Projection {
592 if self.is_globe() {
593 crate::camera::Projection::VerticalPerspective
594 } else {
595 crate::camera::Projection::Mercator
596 }
597 }
598
599 #[must_use]
602 pub fn mercator(&self) -> View {
603 if !self.is_globe() {
604 return self.clone();
605 }
606 View::new(ViewParams { projection_transition: 0.0, ..self.params })
607 }
608
609 #[must_use]
611 pub fn tile_matrix(&self, tile_id: &UnwrappedTileID) -> DMat4 {
612 mercator_tile_matrix(tile_id, self.params.scale)
613 }
614
615 #[must_use]
617 pub fn projection_data_with(&self, tile_id: &UnwrappedTileID, proj_matrix: &DMat4) -> ProjectionData {
618 let mercator_matrix = *proj_matrix * self.tile_matrix(tile_id);
619 self.projection().projection_data(self, tile_id, &mercator_matrix)
620 }
621
622 #[must_use]
624 pub fn projection_data(&self, tile_id: &UnwrappedTileID) -> ProjectionData {
625 self.projection_data_with(tile_id, &self.matrices.projection)
626 }
627
628 #[must_use]
631 pub fn projection_data_for_matrix(&self, tile_id: &UnwrappedTileID, mercator_matrix: &DMat4) -> ProjectionData {
632 self.projection().projection_data(self, tile_id, mercator_matrix)
633 }
634
635 #[must_use]
641 pub fn terrain_min_elevation(&self) -> Option<f64> {
642 self.params.terrain_min_elevation
643 }
644
645 #[must_use]
650 pub fn near_z(&self) -> f64 {
651 match self.params.terrain_min_elevation {
652 Some(_) => f64::from(self.params.size.height) / 50.0,
653 None => 1.0,
654 }
655 }
656
657 #[must_use]
662 pub fn far_z(&self) -> f64 {
663 match self.params.terrain_min_elevation {
664 Some(min_elevation) => self.terrain_far_z(min_elevation),
665 None => self.flat_far_z(),
666 }
667 }
668
669 fn flat_far_z(&self) -> f64 {
671 let camera_to_center_distance = self.camera_to_center_distance();
672
673 let limited_pitch = mln_style::math::clamp_f64(self.params.pitch, 0.0, max_mercator_horizon_angle());
674 let camera_to_sea_level_distance =
675 camera_to_center_distance + self.center_altitude_pixels().abs() / limited_pitch.cos();
676
677 let tan_multiple = mln_style::math::clamp_f64(self.tan_fov_above_center() * limited_pitch.tan(), 0.0, 0.99);
678 let horizon_multiple =
679 mln_style::math::clamp_f64(self.fov_center_to_horizon().tan() * limited_pitch.tan(), 0.0, 0.99);
680
681 let furthest_distance = camera_to_sea_level_distance / (1.0 - tan_multiple.min(horizon_multiple));
684 furthest_distance * 1.01
685 }
686
687 #[must_use]
692 pub fn camera_to_sea_level_distance(&self) -> f64 {
693 let camera_to_center_distance = self.camera_to_center_distance();
694 let limited_pitch = self.params.pitch.min(max_mercator_horizon_angle());
695 f64::max(
696 camera_to_center_distance / 2.0,
697 camera_to_center_distance + self.center_altitude_pixels() / limited_pitch.cos(),
698 )
699 }
700
701 fn terrain_far_z(&self, min_elevation: f64) -> f64 {
706 let params = &self.params;
707 let camera_to_center_distance = self.camera_to_center_distance();
708 let pixels_per_meter = 1.0 / self.meters_per_pixel();
709
710 let center_altitude = self.center_altitude_pixels();
712 let limited_pitch = params.pitch.min(max_mercator_horizon_angle());
713 let camera_to_sea_level_distance = self.camera_to_sea_level_distance();
714 let camera_altitude = params.pitch.cos() * camera_to_center_distance + center_altitude;
715 let lowest =
716 center_altitude.min(min_elevation * pixels_per_meter).min(camera_altitude - 100.0 * pixels_per_meter);
717 let lowest_plane = if lowest < 0.0 {
718 camera_to_sea_level_distance - lowest / limited_pitch.cos()
719 } else {
720 camera_to_sea_level_distance
721 };
722
723 let ground_angle = PI / 2.0 + params.pitch;
727 let distance_past_center = |angle: f64| {
728 angle.sin() * lowest_plane / mln_style::math::clamp_f64(PI - ground_angle - angle, 0.01, PI - 0.01).sin()
729 };
730 let top_half_distance = distance_past_center(self.tan_fov_above_center().atan())
731 .min(distance_past_center(self.fov_center_to_horizon()));
732
733 (limited_pitch.sin() * top_half_distance + lowest_plane) * 1.01
734 }
735
736 fn tan_fov_above_center(&self) -> f64 {
741 let params = &self.params;
742 let half_width = 0.5 * f64::from(params.size.width);
743 let half_height = 0.5 * f64::from(params.size.height);
744 let offset = self.center_offset();
745 let (left, right) = (half_width + offset.x, half_width - offset.x);
747 let (top, bottom) = (half_height + offset.y - params.frustum_offset.top, half_height - offset.y);
748 let up = self.up_the_map();
749 let reach = (up.x * right).max(-up.x * left) + (up.y * top).max(-up.y * bottom);
750 reach / half_height * (params.fov / 2.0).tan()
751 }
752
753 fn fov_center_to_horizon(&self) -> f64 {
761 let camera_to_center = self.camera_to_center_distance();
762 let horizon = self.mercator_horizon();
763 let min_horizon_angle = PI / 2.0 - max_mercator_horizon_angle();
764 if (horizon / camera_to_center).atan() <= min_horizon_angle {
765 return min_horizon_angle;
766 }
767 let offset = self.center_offset();
768 let offset_up = DVec2::new(-offset.x, offset.y).dot(self.up_the_map());
769 let farthest = camera_to_center * (max_mercator_horizon_angle() - self.params.pitch).tan();
770 (mln_style::math::clamp_f64(horizon + offset_up, 0.0, farthest) / camera_to_center).atan()
771 }
772
773 fn up_the_map(&self) -> DVec2 {
777 let (sin, cos) = self.params.roll.sin_cos();
778 let flip = if self.params.viewport_mode == ViewportMode::FlippedY { -1.0 } else { 1.0 };
779 DVec2::from_angle(-self.north_orientation_angle()).rotate(DVec2::new(-sin, flip * cos))
780 }
781
782 #[must_use]
785 pub fn projection_matrix_with(&self, near_z: f64, aligned: bool) -> DMat4 {
786 let params = &self.params;
787 if params.size.is_empty() {
788 return DMat4::ZERO;
789 }
790
791 let offset = self.center_offset();
792 let width = f64::from(params.size.width);
793 let height = f64::from(params.size.height);
794
795 let camera = self.camera_pose();
796 let pixels_per_meter = 1.0 / self.meters_per_pixel();
797 let world_to_camera =
798 camera.world_to_camera(params.scale, pixels_per_meter, params.viewport_mode == ViewportMode::FlippedY);
799 let mut camera_to_clip = perspective(self.perspective_fov(), width / height, near_z, self.far_z());
800
801 if !params.axonometric {
804 camera_to_clip.z_axis.x = -offset.x * 2.0 / width;
805 camera_to_clip.z_axis.y = offset.y * 2.0 / height;
806 }
807
808 if params.north_orientation != NorthOrientation::Upwards {
809 camera_to_clip *= DMat4::from_rotation_z(-self.north_orientation_angle());
810 }
811
812 let mut proj_matrix = camera_to_clip * world_to_camera;
813
814 if params.axonometric {
815 proj_matrix.z_axis.w = 0.0;
817 proj_matrix.z_axis.x = params.x_skew * pixels_per_meter;
818 proj_matrix.z_axis.y = params.y_skew * pixels_per_meter;
819 }
820
821 if aligned {
826 let world_size = Projection::world_size(params.scale);
827 let dx = params.x - 0.5 * world_size;
828 let dy = params.y - 0.5 * world_size;
829
830 let x_shift = f64::from(params.size.width % 2) / 2.0;
831 let y_shift = f64::from(params.size.height % 2) / 2.0;
832 let angle_cos = params.angle.cos();
833 let angle_sin = params.angle.sin();
834 let dxa = -modf_fraction(dx) + angle_cos * x_shift + angle_sin * y_shift;
835 let dya = -modf_fraction(dy) + angle_cos * y_shift + angle_sin * x_shift;
836 proj_matrix *= DMat4::from_translation(DVec3::new(
837 if dxa > 0.5 { dxa - 1.0 } else { dxa },
838 if dya > 0.5 { dya - 1.0 } else { dya },
839 0.0,
840 ));
841 }
842 proj_matrix
843 }
844
845 #[must_use]
848 pub fn projection_matrix(&self) -> DMat4 {
849 self.matrices.projection
850 }
851
852 #[must_use]
853 pub fn inverse_projection_matrix(&self) -> DMat4 {
854 self.matrices.inv_projection
855 }
856
857 #[must_use]
860 pub fn globe_view_projection_matrix(&self) -> DMat4 {
861 self.matrices.globe_view_projection
862 }
863
864 #[must_use]
865 pub fn inverse_globe_view_projection_matrix(&self) -> DMat4 {
866 self.matrices.inv_globe_view_projection
867 }
868
869 #[must_use]
872 pub fn globe_clipping_plane(&self) -> DVec4 {
873 self.matrices.globe_clipping_plane
874 }
875
876 #[must_use]
878 pub fn globe_camera_position(&self) -> DVec3 {
879 self.matrices.globe_camera_position
880 }
881
882 fn center_coordinate(&self) -> DVec3 {
885 let world_size = Projection::world_size(self.params.scale);
886 DVec3::new(
887 (0.5 * world_size - self.params.x) / TILE_SIZE_D,
888 (0.5 * world_size - self.params.y) / TILE_SIZE_D,
889 0.0,
890 )
891 }
892
893 fn coordinate_point_matrix(&self, proj_matrix: &DMat4) -> DMat4 {
895 let size = self.params.size;
896 let pixel_matrix =
897 DMat4::from_scale(DVec3::new(f64::from(size.width) / 2.0, -f64::from(size.height) / 2.0, 1.0))
898 * DMat4::from_translation(DVec3::new(1.0, -1.0, 0.0));
899 pixel_matrix * *proj_matrix * DMat4::from_scale(DVec3::new(TILE_SIZE_D, TILE_SIZE_D, 1.0))
900 }
901
902 #[must_use]
906 pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
907 self.lat_lng_to_screen_coordinate_at(lat_lng, 0.0)
908 }
909
910 #[must_use]
914 pub fn lat_lng_to_screen_coordinate_at(&self, lat_lng: &LatLng, height: f64) -> ScreenCoordinate {
915 self.clip_point_at(lat_lng, height).0
916 }
917
918 #[must_use]
921 pub fn lat_lng_to_screen_coordinate_with_clip(&self, lat_lng: &LatLng) -> (ScreenCoordinate, DVec4) {
922 self.clip_point_at(lat_lng, 0.0)
923 }
924
925 fn clip_point_at(&self, lat_lng: &LatLng, height: f64) -> (ScreenCoordinate, DVec4) {
930 if self.params.size.is_empty() {
931 return (ScreenCoordinate::new(0.0, 0.0), DVec4::ZERO);
932 }
933
934 if self.is_globe() {
935 return VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(self, lat_lng, height);
936 }
937
938 let pt = Projection::project(lat_lng, self.params.scale);
939 let p = self.matrices.coord * DVec4::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D, height, 1.0);
940 (ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w), p)
941 }
942
943 #[must_use]
946 pub fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
947 if self.params.size.is_empty() || !self.is_globe() {
948 return false;
949 }
950 let surface = VerticalPerspectiveProjection::surface_vector(lat_lng);
951 self.globe_clipping_plane().dot(surface.extend(1.0)) < 0.0
952 }
953
954 #[must_use]
957 pub fn screen_coordinate_to_tile_coordinate(&self, point: &ScreenCoordinate, at_zoom: u8) -> TileCoordinate {
958 if self.params.size.is_empty() {
959 return TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 };
960 }
961
962 if self.is_globe() {
963 return match VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(
964 self,
965 point,
966 0.0,
967 WrapMode::Unwrapped,
968 ) {
969 Some(lat_lng) => TileCoordinate::from_lat_lng(f64::from(at_zoom), &lat_lng),
970 None => TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 },
971 };
972 }
973
974 self.mercator_screen_coordinate_to_tile_coordinate(point, at_zoom, 0.0)
975 }
976
977 fn mercator_screen_coordinate_to_tile_coordinate(
981 &self,
982 point: &ScreenCoordinate,
983 at_zoom: u8,
984 height: f64,
985 ) -> TileCoordinate {
986 let flipped_y = f64::from(self.params.size.height) - point.y;
987
988 let inverted = self.matrices.inverted_from_center;
991 let offset0 = inverted.project_point3(DVec3::new(point.x, flipped_y, 0.0));
992 let offset1 = inverted.project_point3(DVec3::new(point.x, flipped_y, 1.0));
993
994 let z0 = offset0.z;
995 let z1 = offset1.z;
996 let t = if z0 <= z1 { 0.0 } else { -(z0 - height) / (z1 - z0) };
998
999 let offset = offset0 + (offset1 - offset0) * t;
1000 let center = self.center_coordinate();
1001 let factor = f64::from(1i32.wrapping_shl(u32::from(at_zoom)));
1002 let scale = self.params.scale;
1003 TileCoordinate {
1004 p: Point::new((center.x + offset.x) / scale * factor, (center.y + offset.y) / scale * factor),
1005 z: f64::from(at_zoom),
1006 }
1007 }
1008
1009 pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
1013 self.screen_coordinate_to_lat_lng_at(point, 0.0, wrap_mode)
1014 }
1015
1016 pub fn screen_coordinate_to_lat_lng_at(
1026 &self,
1027 point: &ScreenCoordinate,
1028 height: f64,
1029 wrap_mode: WrapMode,
1030 ) -> Result<LatLng, Error> {
1031 if self.is_globe() && !self.params.size.is_empty() {
1033 if point.x.is_nan() || point.y.is_nan() {
1034 return Err(Error::invalid_argument("screen coordinate must not be NaN"));
1035 }
1036 if !point.x.is_finite() || !point.y.is_finite() {
1037 return Err(Error::invalid_argument("screen coordinate must not be infinite"));
1038 }
1039 return VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(self, point, height, wrap_mode)
1040 .ok_or_else(|| Error::invalid_argument("the camera shows no location"));
1041 }
1042 let coord = if self.params.size.is_empty() {
1043 self.screen_coordinate_to_tile_coordinate(point, 0)
1044 } else {
1045 self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height)
1046 };
1047 Projection::unproject(&coord.p, 1.0 / TILE_SIZE_D, wrap_mode)
1048 }
1049
1050 #[must_use]
1056 pub fn line_of_sight(&self, point: &ScreenCoordinate) -> Option<(DVec3, DVec3)> {
1057 if self.is_globe() || self.matrices.projection == DMat4::ZERO {
1058 return None;
1059 }
1060 let flipped_y = f64::from(self.params.size.height) - point.y;
1061 let inverted = self.matrices.inverted_from_center;
1064 let center = self.center_coordinate();
1065 let scale = self.params.scale;
1066 let world = |depth: f64| {
1067 let offset = inverted.project_point3(DVec3::new(point.x, flipped_y, depth));
1068 DVec3::new((center.x + offset.x) / scale, (center.y + offset.y) / scale, offset.z)
1069 };
1070 let (near, far) = (world(-1.0), world(1.0));
1071 (near.is_finite() && far.is_finite()).then_some((near, far))
1072 }
1073
1074 #[must_use]
1078 pub fn max_pitch_scale_factor(&self) -> f64 {
1079 if self.params.size.is_empty() {
1080 return 0.0;
1081 }
1082 let corner = self.mercator_screen_coordinate_to_tile_coordinate(
1085 &ScreenCoordinate::new(0.0, f64::from(self.params.size.height)),
1086 0,
1087 0.0,
1088 );
1089 let Ok(lat_lng) = Projection::unproject(&corner.p, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped) else {
1091 return 0.0;
1092 };
1093
1094 let scale = self.params.scale;
1095 let pt = if self.is_globe() {
1096 Point::new(corner.p.x * scale, corner.p.y * scale)
1097 } else {
1098 let pt = Projection::project(&lat_lng, scale);
1099 Point::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D)
1100 };
1101 let top_point = self.matrices.coord * DVec4::new(pt.x, pt.y, 0.0, 1.0);
1102 top_point.w / self.camera_to_center_distance()
1103 }
1104}