use std::f64::consts::PI;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use geometry::Point;
use mln_style::error::Error;
use mln_style::geo::{LatLng, WrapMode};
use mln_style::size::Size;
use mln_style::time::Instant;
use mln_style::types::ProjectionDefinition;
use parking_lot::Mutex;
use crate::camera::{
AnimationOptions, CameraLimits, CameraOptions, CenterAndBearing, ConstrainMode, FreeCameraOptions,
NorthOrientation, ProjectionMode, TransformState, TransitionEnd, VerticalPerspectiveProjection, View, ViewportMode,
};
use crate::geo::constants::M2PI;
use crate::geo::projection::Projection;
use crate::geo::{EdgeInsets, ScreenCoordinate};
use crate::log_target;
mod anchor;
mod animation;
mod gesture;
mod momentum;
mod terrain;
mod transition;
use gesture::GestureState;
pub use terrain::TerrainGround;
pub(crate) use terrain::lowest_ground;
use transition::{FrameFn, JointEnd, Transition};
use crate::map::events::{CameraChange, CameraChangeSource};
pub const STALE_FRAME_TIME: Duration = Duration::from_millis(100);
fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
if angle.is_nan() || anchor_angle.is_nan() {
return 0.0;
}
angle = mln_style::math::wrap(angle, -PI, PI);
if angle == -PI {
angle = PI;
}
let diff = (angle - anchor_angle).abs();
if (angle - M2PI - anchor_angle).abs() < diff {
angle -= M2PI;
}
if (angle + M2PI - anchor_angle).abs() < diff {
angle += M2PI;
}
angle
}
fn lat_lng(lat: f64, lon: f64) -> LatLng {
LatLng::saturating(lat, lon, WrapMode::Unwrapped)
}
fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
if [top, left, bottom, right].iter().any(|value| value.is_nan()) {
log::error!(target: log_target::GENERAL, "an animation frame's insets are NaN");
return None;
}
Some(EdgeInsets::new(top, left, bottom, right))
}
fn frame_unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
Projection::unproject(p, scale, wrap_mode)
.map_err(|e| log::error!(target: log_target::GENERAL, "{}", e.message))
.ok()
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CameraCommandId(u64);
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CommandEnd {
pub command: CameraCommandId,
pub transition_id: Option<u64>,
pub end: TransitionEnd,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TransformEvent {
CameraWillChange(CameraChange),
CameraIsChanging,
CameraDidChange(CameraChange),
CommandEnded(CommandEnd),
}
pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;
const CENTER: u16 = 1 << 0;
const ZOOM: u16 = 1 << 1;
const BEARING: u16 = 1 << 2;
const PITCH: u16 = 1 << 3;
const PADDING: u16 = 1 << 4;
const ALTITUDE: u16 = 1 << 5;
const ROLL: u16 = 1 << 6;
const FOV: u16 = 1 << 7;
fn camera_fields(camera: &CameraOptions) -> u16 {
let field = |set: bool, field: u16| if set { field } else { 0 };
field(camera.center.is_some(), CENTER)
| field(camera.zoom.is_some(), ZOOM)
| field(camera.bearing.is_some(), BEARING)
| field(camera.pitch.is_some(), PITCH)
| field(camera.padding.is_some(), PADDING)
| field(camera.center_altitude.is_some(), ALTITUDE)
| field(camera.roll.is_some(), ROLL)
| field(camera.fov.is_some(), FOV)
}
#[derive(Clone, Debug, Default)]
pub struct FrameClock(Arc<Mutex<Option<Instant>>>);
impl FrameClock {
pub fn set(&self, time: Option<Instant>) {
*self.0.lock() = time;
}
#[must_use]
pub fn get(&self) -> Option<Instant> {
*self.0.lock()
}
}
pub struct Transform {
state: TransformState,
transitions: Vec<Transition>,
events: Vec<TransformEvent>,
command: Option<CameraCommandId>,
silent: bool,
next_command: u64,
joint_ends: Vec<JointEnd>,
source: CameraChangeSource,
gesture: GestureState,
gesture_in_progress: bool,
moving: u16,
frame_time: FrameClock,
projection_for_zoom: Option<ProjectionForZoomFn>,
globe_drag_hold: Option<GlobeDragHold>,
terrain: Option<TerrainGround>,
last_frame: Option<Instant>,
}
#[derive(Clone, Copy, Debug)]
struct GlobeDragHold {
location: LatLng,
height: f64,
cursor: ScreenCoordinate,
camera: CameraOptions,
size: Size,
}
impl Transform {
#[must_use]
pub fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
Self::from_state(TransformState::new(constrain_mode, viewport_mode))
}
pub(crate) fn from_state(state: TransformState) -> Self {
Transform {
state,
transitions: Vec::new(),
events: Vec::new(),
command: None,
silent: false,
next_command: 0,
joint_ends: Vec::new(),
source: CameraChangeSource::Command,
gesture: GestureState::default(),
gesture_in_progress: false,
moving: 0,
frame_time: FrameClock::default(),
projection_for_zoom: None,
globe_drag_hold: None,
terrain: None,
last_frame: None,
}
}
pub fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
self.events.drain(..)
}
#[must_use]
pub fn has_events(&self) -> bool {
!self.events.is_empty()
}
fn emit(&mut self, event: TransformEvent) {
self.events.push(event);
}
pub fn resize(&mut self, size: Size) -> Result<(), Error> {
if size.is_empty() {
return Err(Error::invalid_argument("failed to resize: size is empty"));
}
if self.state.view().size() == size {
return Ok(());
}
self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
self.state.set_size(size);
let (scale, center) = self.state.constrain_screen(self.state.view().scale());
if let Some(center) = center {
if self.in_transition() {
self.cancel_transitions();
}
let zoom = crate::camera::scale_zoom(scale);
self.state.set_lat_lng_zoom(¢er, zoom);
self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
return Ok(());
}
self.state.constrain_position(scale);
self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
Ok(())
}
#[must_use]
pub fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
self.state.camera_options(padding)
}
pub fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
self.command(|transform| transform.jump(camera))
}
fn jump(&mut self, camera: &CameraOptions) {
if self.state.view().is_globe()
&& let Some(center) = camera.center
&& camera.zoom.is_none()
{
let zoom = self.view().zoom()
+ VerticalPerspectiveProjection::zoom_adjustment(
self.view().center(WrapMode::Wrapped).latitude(),
center.latitude(),
);
self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
return;
}
self.ease_to(camera, &AnimationOptions::default());
}
fn globe_on_screen(&self) -> bool {
self.state.view().is_globe() && !self.state.view().size().is_empty()
}
pub fn move_by(
&mut self,
offset: &ScreenCoordinate,
animation: &AnimationOptions,
) -> Result<CameraCommandId, Error> {
self.move_by_with_anchor(offset, None, animation)
}
pub fn move_by_with_anchor(
&mut self,
offset: &ScreenCoordinate,
anchor: Option<ScreenCoordinate>,
animation: &AnimationOptions,
) -> Result<CameraCommandId, Error> {
let mut moved = Ok(());
let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
moved.map(|()| command)
}
fn move_by_now(
&mut self,
offset: &ScreenCoordinate,
anchor: Option<ScreenCoordinate>,
animation: &AnimationOptions,
) -> Result<(), Error> {
let flipped = |state: &TransformState, point: &ScreenCoordinate| {
ScreenCoordinate::new(point.x, f64::from(state.view().size().height) - point.y)
};
let size = self.state.view().size();
let view_center = self.state.view().padding().center_in(size);
let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
let globe = self.globe_on_screen();
if globe && (offset.x.is_nan() || offset.y.is_nan()) {
return Err(Error::invalid_argument("offset must not be NaN"));
}
if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
return Err(Error::invalid_argument("offset must not be infinite"));
}
if globe
&& let Some(duration) = fling_duration
&& self.state.view().globe_free_bearing()
{
let start = CenterAndBearing {
center: self.view().center(WrapMode::Unwrapped),
bearing: -mln_style::math::rad2deg(self.view().angle()),
};
let end = VerticalPerspectiveProjection::fling_camera(
self.state.view(),
&flipped(&self.state, &view_center),
&ScreenCoordinate::new(offset.x, -offset.y),
);
let start_zoom = self.view().zoom();
let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
let center = state.constrained_center(&camera.center, state.view().zoom());
CameraOptions {
center: Some(center),
zoom: Some(
start_zoom
+ VerticalPerspectiveProjection::zoom_adjustment(
start.center.latitude(),
center.latitude(),
),
),
bearing: Some(camera.bearing),
..Default::default()
}
});
let fields = CameraOptions {
center: Some(end.center),
zoom: Some(start_zoom),
bearing: Some(end.bearing),
..Default::default()
};
self.start_transition(&fields, animation, frame, None, duration, false);
return Ok(());
}
if globe && fling_duration.is_some() {
let mut center = self.state.constrained_center(
&VerticalPerspectiveProjection::pan_center(self.state.view(), offset),
self.view().zoom(),
);
let longitude = self.view().center(WrapMode::Unwrapped).longitude();
if (center.longitude() - longitude).abs() > 180.0 {
center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
}
self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
return Ok(());
}
if globe {
let from = anchor.map(|anchor| ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y));
let held = self.globe_drag_hold.take().filter(|held| {
from.is_some_and(|from| (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3)
&& !self.state.view().globe_free_bearing()
&& held.size == size
&& held.camera == self.camera_options(None)
});
let height = match (held, anchor.zip(from)) {
(Some(held), _) => held.height,
(None, Some((anchor, from))) => self.anchor_height(&from, &anchor),
(None, None) => self.view().center_altitude(),
};
let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
VerticalPerspectiveProjection::screen_coordinate_hits_globe(
state.view(),
&flipped(state, point),
height,
)
};
let grab = match anchor {
Some(anchor) if on_globe(&self.state, &anchor) => anchor,
_ => view_center,
};
let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
let mut camera = CameraOptions::default();
let hold = match anchor.zip(from) {
Some((anchor, from)) if !self.state.view().globe_free_bearing() && on_globe(&self.state, &anchor) => {
let location = match held {
Some(held) => Some(held.location),
None if on_globe(&self.state, &from) => self
.state
.view()
.screen_coordinate_to_lat_lng_at(&flipped(&self.state, &from), height, WrapMode::Unwrapped)
.ok(),
None => None,
};
location.and_then(|location| {
VerticalPerspectiveProjection::drag_center_holding(
self.state.view(),
&location,
&flipped(&self.state, &anchor),
height,
)
.map(|center| (location, anchor, center))
})
}
_ => None,
};
let mut center = if let Some((_, _, center)) = hold {
center
} else if self.state.view().globe_free_bearing() {
let drag = VerticalPerspectiveProjection::drag_camera(
self.state.view(),
&flipped(&self.state, &grab),
&pan_delta,
height,
);
camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
drag.center
} else {
VerticalPerspectiveProjection::drag_center(
self.state.view(),
&flipped(&self.state, &grab),
&pan_delta,
height,
)
};
center = self.state.constrained_center(¢er, self.view().zoom());
let zoom = self.view().zoom()
+ VerticalPerspectiveProjection::zoom_adjustment(
self.view().center(WrapMode::Wrapped).latitude(),
center.latitude(),
);
self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
location,
height,
cursor,
camera: self.camera_options(None),
size,
});
return Ok(());
}
let mut center_offset = *offset;
let pitch = self.state.view().pitch();
let offset_length = offset.x.hypot(offset.y);
if pitch > 0.0 && offset_length > 0.0 {
let camera_to_center =
0.5 * f64::from(self.state.view().size().height) / (self.state.view().fov() / 2.0).tan();
let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
let horizon_factor = 0.75;
let scale = pixels_to_horizon * horizon_factor / offset_length;
if scale < 1.0 {
center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
}
}
let size = self.state.view().size();
let center = self.state.view().padding().center_in(size);
let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
let anchored = anchor.and_then(|anchor| {
let grabbed = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
Some((grabbed, anchor, self.anchor_plane(&grabbed, &anchor)?))
});
let (from, to, height) = anchored.unwrap_or((point_on_screen, center, self.view().center_altitude()));
let center = self.center_moving_on_plane(&from, &to, height)?;
self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
Ok(())
}
pub fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
self.state.set_limits(limits)
}
pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
self.state.set_frustum_offset(frustum_offset);
}
pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
self.state.set_projection_definition(definition);
}
pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
self.projection_for_zoom = projection_for_zoom;
}
pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
self.state.set_globe_free_bearing(free_bearing);
}
pub(crate) fn is_globe_free_bearing(&self) -> bool {
self.state.view().globe_free_bearing()
}
#[cfg(test)]
pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
self.state.view().is_location_occluded(lat_lng)
}
pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
self.state.set_north_orientation(orientation);
self.state.constrain_position(self.state.view().scale());
}
pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
self.state.set_constrain_mode(mode);
self.state.constrain_position(self.state.view().scale());
}
pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
self.state.set_viewport_mode(mode);
}
pub fn set_center_clamped_to_ground(&mut self, clamped: bool) {
self.state.set_center_clamped_to_ground(clamped);
}
pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
if let Some(x_skew) = options.x_skew {
self.state.set_x_skew(x_skew);
}
if let Some(y_skew) = options.y_skew {
self.state.set_y_skew(y_skew);
}
if let Some(axonometric) = options.axonometric {
self.state.set_axonometric(axonometric.as_bool());
}
}
pub fn set_frame_time(&mut self, time: Option<Instant>) {
self.frame_time.set(time);
}
pub(crate) fn frame_clock(&self) -> FrameClock {
self.frame_time.clone()
}
pub(crate) fn frame_time(&self) -> Option<Instant> {
self.fresh_frame_time(Instant::now())
}
fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
self.frame_time.get().filter(|&time| now.saturating_duration_since(time) <= STALE_FRAME_TIME)
}
fn now(&self) -> Instant {
let now = Instant::now();
self.fresh_frame_time(now).unwrap_or(now)
}
#[must_use]
pub fn is_camera_moving(&self) -> bool {
self.gesture_in_progress || self.moving & (CENTER | ZOOM | BEARING) != 0
}
#[must_use]
pub fn state(&self) -> &TransformState {
&self.state
}
#[must_use]
pub fn view(&self) -> &View {
self.state.view()
}
#[cfg(test)]
pub(crate) fn is_rotating(&self) -> bool {
self.moving & BEARING != 0
}
#[cfg(test)]
pub(crate) fn is_scaling(&self) -> bool {
self.moving & ZOOM != 0
}
#[cfg(test)]
pub(crate) fn is_panning(&self) -> bool {
self.moving & CENTER != 0
}
#[must_use]
pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
let mut point = self.state.view().lat_lng_to_screen_coordinate(lat_lng);
point.y = f64::from(self.state.view().size().height) - point.y;
point
}
pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
let mut flipped_point = *point;
flipped_point.y = f64::from(self.state.view().size().height) - flipped_point.y;
self.state.view().screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
}
pub(crate) fn screen_coordinate_to_lat_lng_at(
&self,
point: &ScreenCoordinate,
height: f64,
wrap_mode: WrapMode,
) -> Result<LatLng, Error> {
self.view().screen_coordinate_to_lat_lng_at(&flip_y(self.view(), point), height, wrap_mode)
}
pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
self.cancel_transitions();
self.state.set_free_camera_options(options);
}
}
pub(crate) fn flip_y(view: &View, point: &ScreenCoordinate) -> ScreenCoordinate {
ScreenCoordinate::new(point.x, f64::from(view.size().height) - point.y)
}
fn nanos_from_secs(seconds: f64) -> Option<Duration> {
(seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
}
fn max_pitch_for_padding(state: &TransformState, insets: &EdgeInsets) -> f64 {
let center_offset_y = 0.5 * (insets.top - insets.bottom);
if center_offset_y == 0.0 {
return state.limits().max_pitch;
}
let height = state.view().size().height;
debug_assert!(height != 0);
let field_of_view = state.view().fov();
let tangent_of_fov_above_center_angle =
(0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
let fov_above_center = tangent_of_fov_above_center_angle.atan();
f64::max(state.limits().min_pitch, state.limits().max_pitch + field_of_view / 2.0 - fov_above_center)
}
#[cfg(test)]
#[path = "transform_test.rs"]
mod transform_test;