mln-rs-engine 0.0.22

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use mln_style::math::deg2rad;

/// The pitch at which Mercator's horizon reaches the top of the screen, in
/// degrees.
pub(crate) const MAX_MERCATOR_HORIZON_ANGLE_DEGREES: f64 = 89.25;

const ASSUMED_MAX_FEATURE_HEIGHT_METERS: f64 = 500.0;
const TILE_CULLING_HORIZON_ONSET_DEGREES: f64 = 15.0;

fn integral_of_cos_x_by_p(p: f64, x1: f64, x2: f64) -> f64 {
    const NUM_POINTS: i32 = 10;
    let mut sum = 0.0;
    let dx = (x2 - x1) / f64::from(NUM_POINTS);
    for i in 0..NUM_POINTS {
        let x = x1 + (f64::from(i) + 0.5) / f64::from(NUM_POINTS) * (x2 - x1);
        sum += dx * x.cos().powf(p);
    }
    sum
}

/// How many zoom levels apart the tiles at the bottom of the screen and at
/// the horizon may be, at the steepest pitch.
const MAX_ZOOM_LEVELS_ON_SCREEN: f64 = 9.314;

/// How many times the tiles of an unpitched view a pitched view may load
/// before its tiles' zooms drop to keep the count within that.
const TILE_COUNT_MAX_MIN_RATIO: f64 = 3.0;

/// The zoom each tile is loaded at when the view is pitched: finer for tiles
/// nearer the camera, coarser toward the horizon, under a total tile budget.
/// The globe's cover picks its tiles' zooms with it, and Mercator's over
/// terrain.
#[derive(Clone, Copy, Debug)]
pub(crate) struct TileZoomFunction {
    camera_vertical_fov: f64,
    pitch_tile_loading_behavior: f64,
    tile_count_pitch0: f64,
}

impl TileZoomFunction {
    /// The function for a camera of `camera_vertical_fov_degrees`, with the
    /// terms that depend on the field of view alone computed once, for a
    /// whole cover.
    #[must_use]
    pub(crate) fn new(camera_vertical_fov_degrees: f64) -> Self {
        let pitch_tile_loading_behavior = 2.0
            * ((MAX_ZOOM_LEVELS_ON_SCREEN - 1.0)
                / (deg2rad(MAX_MERCATOR_HORIZON_ANGLE_DEGREES - camera_vertical_fov_degrees).cos()
                    / deg2rad(MAX_MERCATOR_HORIZON_ANGLE_DEGREES).cos())
                .log2()
                - 1.0);
        TileZoomFunction {
            camera_vertical_fov: camera_vertical_fov_degrees,
            pitch_tile_loading_behavior,
            tile_count_pitch0: 2.0
                * integral_of_cos_x_by_p(
                    pitch_tile_loading_behavior - 1.0,
                    0.0,
                    deg2rad(camera_vertical_fov_degrees / 2.0),
                ),
        }
    }

    /// The zoom to load a tile at, unrounded: from the zoom asked for at the
    /// center, the camera's distances to the tile, in 2D and along z, and
    /// its distance to the center in 3D, all in one unit.
    #[must_use]
    pub(crate) fn zoom_for(
        &self,
        requested_center_zoom: f64,
        distance_to_tile_2d: f64,
        distance_to_tile_z: f64,
        distance_to_center_3d: f64,
    ) -> f64 {
        let center_pitch = f64::min(1.0, distance_to_tile_z / distance_to_center_3d).acos();
        let highest_pitch = f64::min(
            deg2rad(MAX_MERCATOR_HORIZON_ANGLE_DEGREES),
            center_pitch + deg2rad(self.camera_vertical_fov / 2.0),
        );
        let lowest_pitch = f64::min(highest_pitch, center_pitch - deg2rad(self.camera_vertical_fov / 2.0));
        let tile_count = integral_of_cos_x_by_p(self.pitch_tile_loading_behavior - 1.0, lowest_pitch, highest_pitch);
        let this_tile_pitch = distance_to_tile_2d.atan2(distance_to_tile_z);
        let distance_to_tile_3d = distance_to_tile_2d.hypot(distance_to_tile_z);
        let mut desired = requested_center_zoom;
        desired += (distance_to_center_3d
            / distance_to_tile_3d
            / f64::max(0.5, deg2rad(self.camera_vertical_fov / 2.0).cos()))
        .log2();
        desired += self.pitch_tile_loading_behavior * this_tile_pitch.cos().log2() / 2.0;
        desired -= f64::max(1.0, tile_count / self.tile_count_pitch0 / TILE_COUNT_MAX_MIN_RATIO).log2() / 2.0;
        desired
    }
}

/// Near the bottom of a steeply pitched view, tiles are culled with room for
/// the tallest feature they might hold, so buildings do not vanish before
/// their tile leaves the screen. `center_elevation` is the terrain height under
/// the map center and `max_content_elevation` the tallest content the style is
/// known to hold; both are zero without terrain.
#[must_use]
pub(crate) fn elevation_for_tile_culling(
    pitch_degrees: f64,
    fov_degrees: f64,
    center_elevation: f64,
    max_content_elevation: f64,
) -> f64 {
    let bottom_edge_degrees_above_horizontal = MAX_MERCATOR_HORIZON_ANGLE_DEGREES - pitch_degrees - fov_degrees / 2.0;
    let proximity = (TILE_CULLING_HORIZON_ONSET_DEGREES - bottom_edge_degrees_above_horizontal)
        / TILE_CULLING_HORIZON_ONSET_DEGREES;
    let proximity_to_horizon = proximity.clamp(0.0, 1.0);
    center_elevation + proximity_to_horizon * f64::max(ASSUMED_MAX_FEATURE_HEIGHT_METERS, max_content_elevation)
}

#[cfg(test)]
mod tests {
    use approx::assert_abs_diff_eq;

    use super::{TileZoomFunction, elevation_for_tile_culling};

    /// The culling allowance is zero while the bottom of the view is well
    /// above the horizon, grows as it nears the horizon, and reaches the
    /// tallest feature's height there; it starts from the elevation under
    /// the center, and content taller than the assumed feature raises it.
    #[test]
    fn the_culling_allowance_grows_toward_the_horizon() {
        const FOV: f64 = 36.869_897_645_844_02;
        let allowance = |pitch, center, content| elevation_for_tile_culling(pitch, FOV, center, content);
        assert_abs_diff_eq!(allowance(0.0, 0.0, 0.0), 0.0);
        assert_abs_diff_eq!(allowance(50.0, 0.0, 0.0), 0.0);
        let rising = [60.0, 65.0, 70.0].map(|pitch| allowance(pitch, 0.0, 0.0));
        assert!(0.0 < rising[0] && rising[0] < rising[1] && rising[1] < rising[2] && rising[2] < 500.0, "{rising:?}");
        assert_abs_diff_eq!(allowance(85.0, 0.0, 0.0), 500.0);
        assert_abs_diff_eq!(allowance(85.0, 0.0, 300.0), 500.0);

        let at_70 = rising[2] / 500.0;
        assert_abs_diff_eq!(allowance(70.0, 0.0, 900.0), 900.0 * at_70, epsilon = 1e-9);
        assert_abs_diff_eq!(allowance(70.0, 1200.0, 800.0), 1200.0 + 800.0 * at_70, epsilon = 1e-9);
    }

    #[test]
    fn a_level_camera_over_the_tile_it_is_in_gets_a_zoom() {
        let zoom = TileZoomFunction::new(36.87);
        // At pitch = 90°, camera_coord.z == center_coord.z (distance_z == 0.0)
        // on platforms whose trig leaves no residual, and the root tile contains
        // the camera (distance_to_tile_2d == 0.0).
        let desired = zoom.zoom_for(13.0, 0.0, 0.0, 1e-4);
        assert!(!desired.is_nan() && desired >= 13.0, "desired zoom: {desired}");
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum TileLodMode {
    /// Default `TileLOD` algorithm
    #[default]
    Default,
    /// Distance-based `TileLOD` algorithm
    Distance,
}