mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! The transform's contracts, by what they move: its limits, its
//! conversions, the free camera, commands, momentum, gesture deltas, the
//! globe and registered projections.
//!
//! The transform reports each command's end as an event, which the tests find
//! by the command's transition id (`EndLog`) right after the call that ended
//! it. Commands start at the time that `start_clock` holds the transform's
//! clock at, so a test steps them from a start it knows.

use std::cell::Cell;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

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 mln_style::unitbezier::UnitBezier;

use super::{Transform, TransformEvent};
use crate::camera::{
    AnimationOptions, CameraLimits, CameraMomentum, CameraOptions, ConstrainMode, MomentumDecay, MomentumDecayModel,
    MomentumEasing, MomentumGlide, TransformState, TransitionEnd, TransitionOutcome, VerticalPerspectiveProjection,
};
use crate::geo::projection::Projection;
use crate::geo::{EdgeInsets, ScreenCoordinate};
use crate::map::events::{CameraChange, CameraChangeMode, CameraChangeSource, CameraParts};

mod commands;
mod constraints;
mod conversions;
mod deltas;
mod free_camera;
mod globe;
mod globe_gestures;
mod globe_poles;
mod momentum;
mod registered_projection;

fn new_transform() -> Transform {
    Transform::new(ConstrainMode::HeightOnly)
}

/// A transform of `width` by `height` pixels.
fn sized(width: u32, height: u32) -> Transform {
    let mut transform = new_transform();
    transform.resize(Size::new(width, height)).unwrap();
    transform
}

fn ll(lat: f64, lon: f64) -> LatLng {
    LatLng::new(lat, lon).unwrap()
}

fn sc(x: f64, y: f64) -> ScreenCoordinate {
    ScreenCoordinate::new(x, y)
}

fn insets(top: f64, left: f64, bottom: f64, right: f64) -> EdgeInsets {
    EdgeInsets::new(top, left, bottom, right)
}

fn center(transform: &Transform) -> LatLng {
    transform.view().center(WrapMode::Wrapped)
}

fn unwrapped_center(transform: &Transform) -> LatLng {
    transform.view().center(WrapMode::Unwrapped)
}

fn bearing_degrees(transform: &Transform) -> f64 {
    mln_style::math::rad2deg(-transform.view().angle())
}

fn pitch_degrees(transform: &Transform) -> f64 {
    mln_style::math::rad2deg(transform.view().pitch())
}

/// Changes the transform's limits by `change`.
fn limit(transform: &mut Transform, change: impl FnOnce(&mut CameraLimits)) -> Result<(), Error> {
    let mut limits = *transform.state().limits();
    change(&mut limits);
    transform.set_limits(limits)
}

/// Starts the commands made after it at the returned time, at which it
/// holds the transform's clock.
fn start_clock(transform: &mut Transform) -> Instant {
    crate::tests::hold_clock(&transform.frame_clock())
}

/// Steps the commands started at `start` to `k` seconds in.
fn run_to(transform: &mut Transform, start: Instant, k: f64) {
    transform.update_transitions(Some(start + Duration::from_millis((k * 1000.0) as u64)));
}

/// Steps the commands started at `start` past the end of any of them.
fn run_to_end(transform: &mut Transform, start: Instant) {
    transform.update_transitions(Some(start + Duration::from_hours(24)));
}

/// One second with a linear easing, so a frame at half time is the frame at
/// k = 0.5.
fn linear_second() -> AnimationOptions {
    AnimationOptions {
        duration: Some(Duration::from_millis(1000)),
        easing: Some(UnitBezier::new(0.0, 0.0, 1.0, 1.0)),
        ..AnimationOptions::default()
    }
}

/// An 800 by 600 globe at `center`.
fn globe(center: LatLng, zoom: f64, bearing: f64, pitch: f64) -> Transform {
    globe_of(800, 600, center, zoom, bearing, pitch)
}

/// A 512 by 512 globe at `center`, looking straight down.
fn square_globe(center: LatLng, zoom: f64) -> Transform {
    globe_of(512, 512, center, zoom, 0.0, 0.0)
}

fn globe_of(width: u32, height: u32, center: LatLng, zoom: f64, bearing: f64, pitch: f64) -> Transform {
    let mut transform = sized(width, height);
    transform.set_projection(ProjectionDefinition::from_name("vertical-perspective").into());
    transform.jump_to(&CameraOptions {
        center: Some(center),
        zoom: Some(zoom),
        bearing: Some(bearing),
        pitch: Some(pitch),
        ..Default::default()
    });
    transform
}

/// The globe's radius in pixels for `state`'s camera.
fn globe_radius(state: &TransformState) -> f64 {
    VerticalPerspectiveProjection::globe_radius_pixels(
        Projection::world_size(state.view().scale()),
        state.view().center(WrapMode::Unwrapped).latitude(),
    )
}

/// Finds the ends of the commands with one transition id among what the
/// transform reported.
struct EndLog {
    transition_id: u64,
    /// The ends that [`Self::take_finish`] has seen.
    seen: Cell<usize>,
}

impl EndLog {
    /// Gives `options` a transition id of its own, unless it has one,
    /// whose commands' ends the log finds.
    fn install(options: &mut AnimationOptions) -> EndLog {
        static NEXT: AtomicU64 = AtomicU64::new(1 << 32);
        let transition_id = *options.transition_id.get_or_insert_with(|| NEXT.fetch_add(1, Ordering::Relaxed));
        EndLog { transition_id, seen: Cell::new(0) }
    }

    /// The ends of the log's commands, oldest first.
    fn ends(&self, transform: &Transform) -> Vec<TransitionEnd> {
        transform
            .events
            .iter()
            .filter_map(|event| match event {
                TransformEvent::CommandEnded(end) if end.transition_id == Some(self.transition_id) => Some(end.end),
                _ => None,
            })
            .collect()
    }

    /// How many of the log's commands ended.
    fn count(&self, transform: &Transform) -> usize {
        self.ends(transform).len()
    }

    /// How the log's one command ended, if it has.
    fn get(&self, transform: &Transform) -> Option<TransitionEnd> {
        let ends = self.ends(transform);
        assert!(ends.len() <= 1, "a command ends once");
        ends.first().copied()
    }

    /// Whether a command of the log ended since the last call.
    fn take_finish(&self, transform: &Transform) -> bool {
        let count = self.count(transform);
        count > self.seen.replace(count)
    }
}

/// Animation options, and the log of how their command ended.
fn record_end() -> (AnimationOptions, EndLog) {
    let mut animation = AnimationOptions::default();
    let ended = EndLog::install(&mut animation);
    (animation, ended)
}

fn outcome(transform: &Transform, ended: &EndLog) -> Option<TransitionOutcome> {
    ended.get(transform).map(|end| end.outcome)
}

/// A transform 1000 px square at zoom 8 over null island.
fn zoom_8() -> Transform {
    let mut transform = sized(1000, 1000);
    transform.jump_to(&CameraOptions { center: Some(ll(0.0, 0.0)), zoom: Some(8.0), ..Default::default() });
    transform
}

fn change(mode: CameraChangeMode, source: CameraChangeSource) -> CameraChange {
    CameraChange { mode, source, parts: CameraParts::default() }
}

fn moving(mode: CameraChangeMode, source: CameraChangeSource, parts: CameraParts) -> CameraChange {
    CameraChange { mode, source, parts }
}

const PAN: CameraParts = CameraParts { pan: true, zoom: false, bearing: false, pitch: false };

/// Takes the will-change ('w') and did-change ('d') events that the
/// transform reported, with their changes, and leaves the others.
fn take_changes(transform: &mut Transform) -> Vec<(char, CameraChange)> {
    transform
        .events
        .extract_if(.., |event| {
            matches!(event, TransformEvent::CameraWillChange(_) | TransformEvent::CameraDidChange(_))
        })
        .map(|event| match event {
            TransformEvent::CameraWillChange(change) => ('w', change),
            TransformEvent::CameraDidChange(change) => ('d', change),
            _ => unreachable!(),
        })
        .collect()
}

/// The friction decay rate per second for a half-life.
fn friction_rate(half_life: Duration) -> f64 {
    std::f64::consts::LN_2 / half_life.as_secs_f64()
}

fn friction(half_life: Duration, stop_speed: f64) -> MomentumDecay {
    MomentumDecay { model: MomentumDecayModel::Friction { half_life, stop_speed }, ..MomentumDecay::DEFAULT }
}

/// A curve at an even speed, `reference_speed` units per second for
/// `duration` at that speed, whatever the release.
fn even(reference_speed: f64, duration: Duration) -> MomentumDecay {
    let easing = MomentumEasing { x1: 1.0 / 3.0, y1: 1.0 / 3.0, x2: 2.0 / 3.0, y2: 2.0 / 3.0 };
    MomentumDecay {
        model: MomentumDecayModel::Curve { reference_speed, duration, exponent: 0.0, easing },
        ..MomentumDecay::DEFAULT
    }
}

/// A glide from `velocity` that slows by `friction`.
fn glide<T>(velocity: T, decay: MomentumDecay) -> MomentumGlide<T> {
    MomentumGlide { velocity, decay }
}

/// A glide from `velocity` with the default friction rather than a part's
/// own.
fn plain<T>(velocity: T) -> MomentumGlide<T> {
    glide(velocity, MomentumDecay::DEFAULT)
}

/// A momentum that only pans, from `velocity` by `decay`.
fn panning(velocity: ScreenCoordinate, decay: MomentumDecay) -> CameraMomentum {
    CameraMomentum { pan: Some(glide(velocity, decay)), ..CameraMomentum::default() }
}