1use constants::TILE_SIZE_D;
2use glam::{DQuat, DVec3};
3use mln_style::constants;
4use mln_style::crs::{WorldBox, WorldMapping};
5use mln_style::error::Error;
6use mln_style::geo::{LatLng, LatLngBounds, WrapMode};
7use mln_style::geometry::Point;
8use mln_style::size::Size;
9
10use crate::camera::camera::{CameraOptions, FreeCameraOptions};
11use crate::camera::camera_limits::CameraLimits;
12use crate::camera::camera_pose::CameraPose;
13use crate::camera::ground::GroundHit;
14use crate::camera::map_view::ViewProjection;
15use crate::camera::mode::ConstrainMode;
16use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
17use crate::camera::view::{
18 NorthOrientation, View, ViewParams, center_offset, max_mercator_horizon_angle, scale_zoom, zoom_scale,
19};
20use crate::geo::projection::Projection;
21use crate::geo::{EdgeInsets, ScreenCoordinate};
22
23const WORLD_SQUARE: WorldBox = WorldBox { min: Point::new(0.0, 0.0), max: Point::new(1.0, 1.0) };
25
26fn center_world_box(world: &WorldMapping, bounds: &LatLngBounds) -> WorldBox {
30 if world.wraps() || *bounds == LatLngBounds::default() {
31 return WORLD_SQUARE;
32 }
33 let world_box = world.lng_lat_box_to_world_box(bounds);
34 let WorldBox { min, max } = world_box;
35 if [min.x, min.y, max.x, max.y].iter().all(|edge| edge.is_finite()) { world_box } else { WORLD_SQUARE }
36}
37
38#[derive(Clone, Debug, PartialEq)]
43pub struct TransformState {
44 view: View,
45 limits: CameraLimits,
46 center_world_box: WorldBox,
49}
50
51impl Default for TransformState {
52 fn default() -> Self {
53 TransformState::new(ConstrainMode::HeightOnly)
54 }
55}
56
57impl TransformState {
58 #[must_use]
59 pub(crate) fn new(constrain_mode: ConstrainMode) -> Self {
60 TransformState {
61 view: View::new(ViewParams::new(constrain_mode)),
62 limits: CameraLimits::default(),
63 center_world_box: WORLD_SQUARE,
64 }
65 }
66
67 pub(crate) fn from_parts(params: ViewParams, limits: CameraLimits) -> Self {
69 let center_world_box = center_world_box(params.projection.world(), &limits.bounds);
70 let mut state = TransformState { view: View::new(params), limits, center_world_box };
71 state.update(|_| ());
72 state
73 }
74
75 #[must_use]
77 pub fn view(&self) -> &View {
78 &self.view
79 }
80
81 fn update(&mut self, change: impl FnOnce(&mut ViewParams)) {
84 let mut params = self.view.params().clone();
85 change(&mut params);
86 params.center_wrap = if params.projection.transition() > 0.0 && self.limits.bounds == LatLngBounds::default() {
87 WrapMode::Wrapped
88 } else {
89 WrapMode::Unwrapped
90 };
91 if params != *self.view.params() {
92 self.view = View::new(params);
93 }
94 }
95
96 pub fn set_projection(&mut self, projection: ViewProjection) {
102 if projection == self.view.params().projection {
103 return;
104 }
105 let previous_transition = self.view.projection_transition();
106 let center = (projection.world() != self.view.world()).then(|| self.view.center(WrapMode::Unwrapped));
108 let zoom = self.view.zoom();
109 self.update(|p| p.projection = projection);
110 if let Some(center) = center {
111 self.center_world_box = center_world_box(self.view.world(), &self.limits.bounds);
112 self.set_lat_lng_zoom(¢er, zoom);
113 return;
114 }
115 let leaves_globe = self.view.projection_transition() == 0.0 && previous_transition > 0.0;
119 if leaves_globe && !self.view.size().is_empty() {
120 let wrap_mode =
121 if self.limits.bounds == LatLngBounds::default() { WrapMode::Wrapped } else { WrapMode::Unwrapped };
122 let center = self.view.center(wrap_mode);
123 self.set_lat_lng_zoom(¢er, zoom);
124 }
125 }
126
127 fn update_state_from_camera(&mut self, camera: &CameraPose) {
130 let position = camera.position;
131 let DVec3 { x: dx, y: dy, z: dz } = camera.forward();
132
133 let (new_roll, mut new_pitch, new_bearing) = camera.orientation_angles();
134 new_pitch = mln_style::math::clamp_f64(new_pitch, self.limits.min_pitch, self.limits.max_pitch);
135
136 let center_distance = self.view.camera_to_center_distance();
139 let zoom;
140 let travel;
141 if dz < -1.0e-9 && position.z > 1.0e-9 && new_pitch <= max_mercator_horizon_angle() {
142 zoom = (center_distance / (position.z / new_pitch.cos() * TILE_SIZE_D)).log2();
143 travel = -position.z / dz;
144 } else {
145 zoom = 14.0;
146 let new_scale = mln_style::math::clamp_f64(2.0f64.powf(zoom), self.min_scale(), self.max_scale());
147 travel = center_distance / new_scale / TILE_SIZE_D;
148 }
149
150 let world_point = Point::new(position.x + dx * travel, position.y + dy * travel);
151 let Ok(center) = self.view.world().lat_lng_from_world(&world_point) else {
152 return;
153 };
154 let zoom = f64::min(zoom, self.limits.max_zoom);
155 self.set_lat_lng_zoom(¢er, zoom);
156
157 let world_z = position.z + dz * travel;
159 let alt_m = world_z * self.view.world().height_meters_per_world_unit(&self.view.center(WrapMode::Unwrapped));
160 self.set_center_altitude(alt_m);
161 self.set_angle(new_bearing);
162 self.set_pitch(new_pitch);
163 self.set_roll(new_roll);
164 }
165
166 fn constrained_camera_position(&self, position: DVec3) -> Option<DVec3> {
169 if position.is_nan() {
170 return None;
171 }
172 let max_world_size = Projection::world_size(2.0f64.powf(self.limits.max_zoom));
173 let min_world_size = Projection::world_size(2.0f64.powf(self.min_zoom()));
174 let dist_to_center = self.view.camera_to_center_distance();
175 Some(DVec3::new(
176 position.x,
177 position.y,
178 mln_style::math::clamp_f64(position.z, dist_to_center / max_world_size, dist_to_center / min_world_size),
179 ))
180 }
181
182 fn constrained_camera_orientation(orientation: DQuat) -> Option<DQuat> {
186 if orientation.is_nan() || orientation.length() == 0.0 {
187 return None;
188 }
189 let unit_quat = orientation.normalize();
190 CameraPose::orientation_from_frame(unit_quat * DVec3::NEG_Z, unit_quat * DVec3::NEG_Y)
191 }
192
193 pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
194 if !self.is_valid() {
195 return;
196 }
197
198 let mut camera = self.view.camera_pose();
199 let mut changed = false;
200 if let Some(orientation) = options.orientation
201 && orientation != camera.orientation
202 && let Some(orientation) = Self::constrained_camera_orientation(orientation)
203 {
204 camera.orientation = orientation;
205 changed = true;
206 }
207
208 if let Some(position) = options.position
209 && position != camera.position
210 && let Some(position) = self.constrained_camera_position(position)
211 {
212 camera.position = position;
213 changed = true;
214 }
215
216 if changed {
217 self.update_state_from_camera(&camera);
218 }
219 }
220
221 pub fn set_size(&mut self, size: Size) {
224 self.update(|p| p.size = size);
225 }
226
227 pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
228 self.update(|p| p.frustum_offset = *frustum_offset);
229 }
230
231 pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
232 self.update(|p| p.north_orientation = orientation);
233 }
234
235 #[must_use]
236 pub(crate) fn constrain_mode(&self) -> ConstrainMode {
237 self.view.params().constrain_mode
238 }
239
240 pub(crate) fn set_constrain_mode(&mut self, mode: ConstrainMode) {
241 self.update(|p| p.constrain_mode = mode);
242 }
243
244 pub(crate) fn set_center_clamped_to_ground(&mut self, clamped: bool) {
245 self.update(|p| p.center_clamped_to_ground = clamped);
246 }
247
248 pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
249 self.update(|p| p.globe_free_bearing = free_bearing);
250 }
251
252 pub(crate) fn set_padding(&mut self, padding: &EdgeInsets) {
253 self.update(|p| p.padding = *padding);
254 }
255
256 #[must_use]
260 pub(crate) fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
261 let mut camera = self.view.camera();
262 if let Some(padding) = padding {
263 camera.padding = padding;
264 }
265 CameraOptions::from(camera)
266 }
267
268 #[must_use]
274 pub(crate) fn min_zoom_at_latitude(&self, latitude: f64) -> f64 {
275 self.min_zoom_at_latitude_with(latitude, self.view.is_globe())
276 }
277
278 #[must_use]
281 pub(crate) fn min_zoom_at_latitude_with(&self, latitude: f64, globe: bool) -> f64 {
282 if !globe {
283 return self.min_zoom();
284 }
285 scale_zoom(self.min_scale()) + VerticalPerspectiveProjection::zoom_adjustment(0.0, latitude)
288 }
289
290 #[must_use]
293 pub(crate) fn constrained_center(&self, lat_lng: &LatLng, zoom: f64) -> LatLng {
294 if self.constrain_mode() == ConstrainMode::None || !self.view.is_globe() {
295 return *lat_lng;
296 }
297 let max_latitude = VerticalPerspectiveProjection::max_latitude(
298 &self.view,
299 mln_style::math::clamp_f64(zoom, self.min_zoom_at_latitude(lat_lng.latitude()), self.limits.max_zoom),
300 );
301 LatLng::saturating(
302 mln_style::math::clamp_f64(lat_lng.latitude(), -max_latitude, max_latitude),
303 lat_lng.longitude(),
304 WrapMode::Unwrapped,
305 )
306 }
307
308 #[must_use]
312 pub fn limits(&self) -> &CameraLimits {
313 &self.limits
314 }
315
316 pub fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
321 let limits = limits.validated()?;
322 let least_scale = self.constrain(zoom_scale(limits.min_zoom), self.view.x(), self.view.y()).0;
324 if zoom_scale(limits.max_zoom) < least_scale {
325 return Err(Error::invalid_argument("the maximum zoom must be at least the least zoom the view allows"));
326 }
327 let bounds_changed = limits.bounds != self.limits.bounds;
328 self.limits = limits;
329 if bounds_changed {
330 self.center_world_box = center_world_box(self.view.world(), &self.limits.bounds);
331 let lat_lng = self.view.center(WrapMode::Unwrapped);
332 let zoom = self.view.zoom();
333 self.set_lat_lng_zoom(&lat_lng, zoom);
334 self.update(|_| ());
335 }
336 Ok(())
337 }
338
339 fn min_scale(&self) -> f64 {
340 zoom_scale(self.limits.min_zoom)
341 }
342
343 fn max_scale(&self) -> f64 {
344 zoom_scale(self.limits.max_zoom)
345 }
346
347 #[must_use]
350 pub fn min_zoom(&self) -> f64 {
351 scale_zoom(self.constrained_min_scale())
352 }
353
354 fn constrained_min_scale(&self) -> f64 {
355 self.constrain(self.min_scale(), self.view.x(), self.view.y()).0
356 }
357
358 pub fn set_angle(&mut self, angle: f64) {
363 if angle.is_finite() {
364 self.update(|p| p.angle = angle);
365 }
366 }
367
368 pub(crate) fn set_fov(&mut self, fov: f64) {
369 if fov.is_finite() {
370 self.update(|p| p.fov = fov);
371 }
372 }
373
374 pub(crate) fn set_roll(&mut self, roll: f64) {
375 if roll.is_finite() {
376 self.update(|p| p.roll = roll);
377 }
378 }
379
380 pub fn set_pitch(&mut self, pitch: f64) {
381 if pitch.is_finite() {
382 self.update(|p| p.pitch = pitch);
383 }
384 }
385
386 pub(crate) fn set_x_skew(&mut self, skew: f64) {
387 if skew.is_finite() {
388 self.update(|p| p.x_skew = skew);
389 }
390 }
391
392 pub(crate) fn set_y_skew(&mut self, skew: f64) {
393 if skew.is_finite() {
394 self.update(|p| p.y_skew = skew);
395 }
396 }
397
398 pub(crate) fn set_axonometric(&mut self, axonometric: bool) {
399 self.update(|p| p.axonometric = axonometric);
400 }
401
402 #[must_use]
408 pub(crate) fn is_valid(&self) -> bool {
409 let scale = self.view.scale();
410 self.view.is_valid()
411 && (if self.view.is_globe() { scale > 0.0 } else { scale >= self.min_scale() })
412 && scale <= self.max_scale()
413 }
414
415 fn rotated_north(&self) -> bool {
418 matches!(self.view.north_orientation(), NorthOrientation::Leftwards | NorthOrientation::Rightwards)
419 }
420
421 #[must_use]
425 pub(crate) fn constrain_screen(&self, scale: f64) -> (f64, Option<LatLng>) {
426 if self.constrain_mode() != ConstrainMode::Screen {
427 return (scale, None);
428 }
429 let mut zoom = scale_zoom(scale);
430 let mut options = CameraOptions::default();
431 self.constrain_camera_and_zoom_to_bounds(&mut options, &mut zoom);
432 (zoom_scale(zoom), options.center)
433 }
434
435 #[must_use]
438 pub(crate) fn constrain(&self, mut scale: f64, mut x: f64, mut y: f64) -> (f64, f64, f64) {
439 let constrain_mode = self.constrain_mode();
440 if constrain_mode == ConstrainMode::None || constrain_mode == ConstrainMode::Screen {
441 return (scale, x, y);
442 }
443
444 if !self.view.world().wraps() {
449 let world_size = Projection::world_size(scale);
450 let WorldBox { min, max } = self.center_world_box;
451 let x =
452 mln_style::math::clamp_f64(x, (0.5 - max.x.min(1.0)) * world_size, (0.5 - min.x.max(0.0)) * world_size);
453 let y =
454 mln_style::math::clamp_f64(y, (0.5 - max.y.min(1.0)) * world_size, (0.5 - min.y.max(0.0)) * world_size);
455 return (scale, x, y);
456 }
457
458 if self.view.is_globe() {
461 let max_latitude = VerticalPerspectiveProjection::max_latitude(&self.view, scale_zoom(scale));
462 let at_max = LatLng::saturating(max_latitude, 0.0, WrapMode::Unwrapped);
463 let max_y = center_offset(self.view.world(), &at_max, scale).map_or(f64::INFINITY, |(_, max_y)| max_y);
464 y = mln_style::math::clamp_f64(y, -max_y, max_y);
465 return (scale, x, y);
466 }
467
468 let size = self.view.size();
469 let width = f64::from(size.width);
470 let height = f64::from(size.height);
471
472 let ratio_y = (if self.rotated_north() { width } else { height }) / TILE_SIZE_D;
475 scale = mln_style::math::fmax(scale, ratio_y);
476
477 let max_y = (scale * TILE_SIZE_D - (if self.rotated_north() { width } else { height })) / 2.0;
479 y = f64::max(-max_y, f64::min(y, max_y));
480
481 if constrain_mode == ConstrainMode::WidthAndHeight {
482 let max_x = (scale * TILE_SIZE_D - (if self.rotated_north() { height } else { width })) / 2.0;
484 x = f64::max(-max_x, f64::min(x, max_x));
485 }
486 (scale, x, y)
487 }
488
489 pub(crate) fn constrain_position(&mut self, scale: f64) {
492 let (scale, x, y) = self.constrain(scale, self.view.x(), self.view.y());
493 if scale.is_finite() && x.is_finite() && y.is_finite() {
494 self.update(|p| {
495 p.scale = scale;
496 p.x = x;
497 p.y = y;
498 });
499 }
500 }
501
502 pub(crate) fn constrain_camera_and_zoom_to_bounds(
503 &self,
504 requested_camera: &mut CameraOptions,
505 requested_zoom: &mut f64,
506 ) {
507 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
508 return;
509 }
510
511 let view = &self.view;
512 let current_center = view.center(WrapMode::Unwrapped);
513 let center_lat_lng = requested_camera.center.unwrap_or(current_center);
514
515 let mut anchor_offset = Point::new(0.0, 0.0);
516 let requested_scale = zoom_scale(*requested_zoom);
517
518 if let Some(mut anchor) = requested_camera.anchor {
522 anchor.y = f64::from(view.size().height) - anchor.y;
523 let mut state = self.clone();
525 state.set_lat_lng_zoom(¤t_center, scale_zoom(requested_scale));
526 if let (Ok(anchor_lat_lng), Ok(screen_lat_lng)) = (
529 view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
530 state.view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
531 ) {
532 let lat_lng_coord = view.world().project(&anchor_lat_lng, requested_scale);
533 let anchor_coord = view.world().project(&screen_lat_lng, requested_scale);
534 anchor_offset = Point::new(lat_lng_coord.x - anchor_coord.x, lat_lng_coord.y - anchor_coord.y);
535 }
536 }
537
538 let (ne_bounds, sw_bounds) = self.bounds_corners(requested_scale);
539 let center = view.world().project(¢er_lat_lng, requested_scale);
540 let current_center = view.world().project(¤t_center, requested_scale);
541
542 let min_y = ne_bounds.y;
543 let max_y = sw_bounds.y;
544 let min_x = sw_bounds.x;
545 let max_x = ne_bounds.x;
546
547 let start_x = center.x;
548 let start_y = center.y;
549
550 let mut result_x = start_x;
551 let mut result_y = start_y;
552
553 let screen_width = view.size().width;
554 let screen_height = view.size().height;
555
556 let h2 = f64::from(screen_height) / 2.0;
557 if start_y - h2 + anchor_offset.y < min_y {
558 result_y = min_y + h2;
559 }
560 if start_y + anchor_offset.y + h2 > max_y {
561 result_y = max_y - h2;
562 }
563
564 let w2 = f64::from(screen_width) / 2.0;
565 if start_x + anchor_offset.x - w2 < min_x {
566 result_x = min_x + w2;
567 }
568 if start_x + anchor_offset.x + w2 > max_x {
569 result_x = max_x - w2;
570 }
571
572 let mut scale_y = 0.0;
573 if max_y - min_y < f64::from(screen_height) {
574 scale_y = f64::from(screen_height) / (max_y - min_y);
575 result_y = f64::midpoint(max_y, min_y);
576 }
577
578 let mut scale_x = 0.0;
579 if max_x - min_x < f64::from(screen_width) {
580 scale_x = f64::from(screen_width) / (max_x - min_x);
581 result_x = f64::midpoint(max_x, min_x);
582 }
583
584 let max_scale = if scale_x > scale_y { scale_x } else { scale_y };
585
586 if max_scale > 1.000_001 {
591 *requested_zoom += scale_zoom(max_scale);
592
593 if scale_y > scale_x {
594 result_x = current_center.x;
597 } else {
598 result_y = current_center.y;
601 }
602
603 if result_x * max_scale - w2 <= min_x * max_scale {
609 result_x = min_x * max_scale + w2;
610 result_x /= max_scale;
611 } else if result_x * max_scale + w2 >= max_x * max_scale {
612 result_x = max_x * max_scale - w2;
613 result_x /= max_scale;
614 }
615
616 if result_y * max_scale - h2 <= min_y * max_scale {
617 result_y = min_y * max_scale + h2;
618 result_y /= max_scale;
619 } else if result_y * max_scale + h2 >= max_y * max_scale {
620 result_y = max_y * max_scale - h2;
621 result_y /= max_scale;
622 }
623 }
624
625 if result_x != start_x || result_y != start_y {
626 requested_camera.anchor = None;
628 requested_camera.center =
630 view.world().unproject(&Point::new(result_x, result_y), requested_scale, WrapMode::Unwrapped).ok();
631 }
632 }
633
634 fn bounds_corners(&self, scale: f64) -> (Point<f64>, Point<f64>) {
638 let world = self.view.world();
639 if world.wraps() {
640 let bounds = &self.limits.bounds;
641 return (world.project(&bounds.northeast(), scale), world.project(&bounds.southwest(), scale));
642 }
643 let world_size = Projection::world_size(scale);
644 let WorldBox { min, max } = self.center_world_box;
645 (
646 Point::new(max.x.min(1.0) * world_size, min.y.max(0.0) * world_size),
647 Point::new(min.x.max(0.0) * world_size, max.y.min(1.0) * world_size),
648 )
649 }
650
651 #[must_use]
656 pub(crate) fn min_zoom_for_screen_bounds(&self) -> Option<f64> {
657 if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
658 return None;
659 }
660 let (ne, sw) = self.bounds_corners(1.0);
663 let size = self.view.size();
664 let scale_x = f64::from(size.width) / (ne.x - sw.x);
665 let scale_y = f64::from(size.height) / (sw.y - ne.y);
666 Some(scale_zoom(f64::max(scale_x, scale_y)))
667 }
668
669 #[cfg(test)]
676 pub(crate) fn move_lat_lng(&mut self, lat_lng: &LatLng, anchor: &ScreenCoordinate) -> Result<(), Error> {
677 self.move_lat_lng_at(lat_lng, anchor, 0.0)
678 }
679
680 pub(crate) fn move_lat_lng_at(
688 &mut self,
689 lat_lng: &LatLng,
690 anchor: &ScreenCoordinate,
691 height: f64,
692 ) -> Result<(), Error> {
693 let view = &self.view;
694 if view.is_globe() {
695 if let Some(center) =
696 VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
697 {
698 let target = self.constrained_center(¢er, view.zoom());
699 let zoom = view.zoom()
700 + VerticalPerspectiveProjection::zoom_adjustment(
701 view.center(WrapMode::Unwrapped).latitude(),
702 target.latitude(),
703 );
704 self.set_lat_lng_zoom(&target, zoom);
705 }
706 return Ok(());
707 }
708 let center = self.center_for_lat_lng_at(lat_lng, anchor, height)?;
709 let target =
712 if self.limits.bounds == LatLngBounds::default() { self.view.world().wrap(center) } else { center };
713 let zoom = self.view.zoom();
714 self.set_lat_lng_zoom(&target, zoom);
715 Ok(())
716 }
717
718 pub(crate) fn center_for_lat_lng_at(
729 &self,
730 lat_lng: &LatLng,
731 anchor: &ScreenCoordinate,
732 height: f64,
733 ) -> Result<LatLng, Error> {
734 let view = &self.view;
735 if view.is_globe() && !view.size().is_empty() {
736 return VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
737 .ok_or_else(|| Error::invalid_argument("no center holds the location at the point"));
738 }
739 let scale = view.scale();
740 let world = view.world();
741 let center_coord = world.project(&view.center(WrapMode::Unwrapped), scale);
742 let lat_lng_coord = world.project(lat_lng, scale);
743 let anchor_coord =
744 world.project(&view.screen_coordinate_to_lat_lng_at(anchor, height, WrapMode::Unwrapped)?, scale);
745 world.unproject(
746 &Point::new(
747 center_coord.x + lat_lng_coord.x - anchor_coord.x,
748 center_coord.y + lat_lng_coord.y - anchor_coord.y,
749 ),
750 scale,
751 WrapMode::Unwrapped,
752 )
753 }
754
755 pub fn set_lat_lng_zoom(&mut self, lat_lng: &LatLng, zoom: f64) {
756 if !zoom.is_finite() {
757 return;
758 }
759 let globe = self.view.is_globe();
760 if !self.view.world().wraps() {
761 let scale = mln_style::math::clamp_f64(zoom_scale(zoom), self.constrained_min_scale(), self.max_scale());
764 let Some((x, y)) = center_offset(self.view.world(), lat_lng, scale) else {
765 return;
766 };
767 let (scale, x, y) = self.constrain(scale, x, y);
768 self.update(|p| {
769 p.scale = scale;
770 p.x = x;
771 p.y = y;
772 });
773 return;
774 }
775 let mut requested = *lat_lng;
776 if globe && self.limits.bounds != LatLngBounds::default() {
780 let turns =
781 ((self.limits.bounds.center().longitude() - lat_lng.longitude()) / constants::DEGREES_MAX).round();
782 requested = LatLng::saturating(
783 lat_lng.latitude(),
784 lat_lng.longitude() + turns * constants::DEGREES_MAX,
785 WrapMode::Unwrapped,
786 );
787 }
788 let mut constrained = self.limits.bounds.constrain(&requested);
789 if globe && self.limits.bounds == LatLngBounds::default() {
793 let current = self.view.center(WrapMode::Unwrapped).longitude();
794 if current.is_finite() {
795 let turns = ((current - constrained.longitude()) / constants::DEGREES_MAX).round();
796 constrained = LatLng::saturating(
797 constrained.latitude(),
798 constrained.longitude() + turns * constants::DEGREES_MAX,
799 WrapMode::Unwrapped,
800 );
801 }
802 }
803
804 let min_scale = if globe {
805 zoom_scale(self.min_zoom_at_latitude(constrained.latitude()))
806 } else {
807 self.constrained_min_scale()
808 };
809 let new_scale = mln_style::math::clamp_f64(zoom_scale(zoom), min_scale, self.max_scale());
810 let Some((x, y)) = center_offset(self.view.world(), &constrained, new_scale) else {
812 return;
813 };
814 let (scale, x, y) = self.constrain(new_scale, x, y);
815 self.update(|p| {
816 p.scale = scale;
817 p.x = x;
818 p.y = y;
819 });
820 }
821
822 pub(crate) fn set_center_altitude(&mut self, alt_m: f64) {
825 if !alt_m.is_finite() {
826 return;
827 }
828 self.update(|p| p.center_altitude = alt_m);
829 }
830
831 pub(crate) fn set_terrain_min_elevation(&mut self, min_elevation: Option<f64>) {
836 if min_elevation.is_some_and(|min| !min.is_finite()) {
837 return;
838 }
839 self.update(|p| p.terrain_min_elevation = min_elevation);
840 }
841
842 pub(crate) fn raise_eye(&mut self, lift: f64) -> bool {
851 let view = &self.view;
852 if !lift.is_finite() || !view.is_valid() {
853 return false;
854 }
855 let distance = view.camera_to_center_distance();
858 let across = view.pitch().sin() * distance;
859 let up = view.pitch().cos() * distance + lift / Self::height_meters_per_pixel(view);
860 let raised = across.hypot(up);
861 if raised == 0.0 {
862 return false;
863 }
864 let pitch = mln_style::math::clamp_f64(across.atan2(up), self.limits.min_pitch, self.limits.max_pitch);
865 let zoom = view.zoom() + (distance / raised).log2();
866 let center = view.center(WrapMode::Unwrapped);
867 let before = view.params().clone();
868 self.set_pitch(pitch);
869 self.set_lat_lng_zoom(¢er, zoom);
870 *self.view.params() != before
871 }
872
873 pub(crate) fn recenter_on(&mut self, hit: &GroundHit) -> bool {
897 let view = &self.view;
898 if !view.is_valid() {
899 return false;
900 }
901 let recentered =
902 if view.is_globe() { Self::recentered_on_sphere(view, hit) } else { self.recentered_on_plane(hit) };
903 let Some((center, altitude, zoom)) = recentered else { return false };
904
905 let mut moved = self.clone();
906 moved.set_center_altitude(altitude);
907 moved.set_lat_lng_zoom(¢er, zoom);
908 let landed = moved.view.center(WrapMode::Unwrapped);
910 let mut on_screen = CameraOptions { center: Some(landed), ..CameraOptions::default() };
911 let mut screen_zoom = moved.view.zoom();
912 moved.constrain_camera_and_zoom_to_bounds(&mut on_screen, &mut screen_zoom);
913 let refused = (moved.view.zoom() - zoom).abs() > 1e-9
914 || (landed.latitude() - center.latitude()).abs() > 1e-9
915 || (landed.longitude() - center.longitude()).abs() > 1e-9
916 || on_screen.center != Some(landed)
917 || screen_zoom != moved.view.zoom();
918 if refused {
919 return false;
920 }
921 *self = moved;
922 true
923 }
924
925 fn recentered_on_plane(&self, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
928 let view = &self.view;
929 let mapping = view.world();
930 let eye = view.eye_position();
931 let forward = view.camera_pose().forward();
932 let meters = mapping.height_meters_per_world_unit(&hit.location(mapping, WrapMode::Unwrapped));
934 let to_hit = DVec3::new((hit.world.x - eye.x) * meters, (hit.world.y - eye.y) * meters, hit.height - eye.z);
935 let distance = to_hit.dot(forward);
936 if !(distance.is_finite() && distance > 0.0) {
937 return None;
938 }
939 let world = Point::new(eye.x + forward.x * distance / meters, eye.y + forward.y * distance / meters);
940 let center = mapping.unproject(&world, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped).ok()?;
941 let center = if self.limits.bounds == LatLngBounds::default() { mapping.wrap(center) } else { center };
944 let zoom = scale_zoom(view.camera_to_center_distance() * meters / distance / TILE_SIZE_D);
945 Some((center, eye.z + forward.z * distance, zoom))
946 }
947
948 fn recentered_on_sphere(view: &View, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
952 let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
953 let eye = view.globe_camera_position();
954 let center = VerticalPerspectiveProjection::surface_vector(&view.center(WrapMode::Unwrapped))
955 * radius(view.center_altitude());
956 let forward = (center - eye).normalize();
957 let target = VerticalPerspectiveProjection::surface_vector(&hit.location(view.world(), WrapMode::Unwrapped))
958 * radius(hit.height);
959 let distance = (target - eye).dot(forward);
960 if !(distance.is_finite() && distance > 0.0) {
961 return None;
962 }
963 let point = eye + forward * distance;
964 let length = point.length();
965 let location = VerticalPerspectiveProjection::surface_vector_to_lat_lng(point / length)?;
966 let location = view.lat_lng_near_center(&location);
967 let radius_at_zoom_0 =
968 VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(1.0), location.latitude());
969 let zoom = scale_zoom(view.camera_to_center_distance() / distance / radius_at_zoom_0);
970 Some((location, (length - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS, zoom))
971 }
972
973 fn height_meters_per_pixel(view: &View) -> f64 {
977 if view.is_globe() {
978 let latitude = view.center(WrapMode::Unwrapped).latitude();
979 VerticalPerspectiveProjection::GLOBE_RADIUS_METERS
980 / VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(view.scale()), latitude)
981 } else {
982 view.meters_per_pixel()
983 }
984 }
985}
986
987#[cfg(test)]
988#[path = "transform_state_test.rs"]
989mod transform_state_test;