mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
//! The fog over the terrain's surface, from the style's `sky`.

use mln_style::color::Color;

use crate::camera::View;
use crate::render::sky::EvaluatedSky;
use crate::render::terrain::ubo::TerrainFog;

/// The fog over the surface in `view` under `sky`, or none without a sky.
///
/// The fog's depth runs from the camera's distance to sea level to the far
/// plane, which the view fits to its horizon. A view
/// pitched less than 60° shows no horizon, and its far plane is just past
/// the top of the view, so the fog fades in from 60° to 70°. It fades out
/// as the view turns to the globe, whose atmosphere covers its limb.
pub(crate) fn terrain_fog(sky: Option<&EvaluatedSky>, view: &View) -> TerrainFog {
    let Some(sky) = sky else {
        return TerrainFog::NONE;
    };
    let pitch = view.pitch().to_degrees();
    let opacity = ((pitch - 60.0) / 10.0).clamp(0.0, 1.0) * (1.0 - view.projection_transition()).clamp(0.0, 1.0);
    if opacity <= 0.0 {
        return TerrainFog::NONE;
    }
    let opacity = opacity as f32;
    TerrainFog {
        fog_color: linear(sky.sky_fog_color.uniform(), opacity),
        horizon_color: linear(sky.sky_horizon_color.uniform(), opacity),
        depth_range: [view.camera_to_sea_level_distance() as f32, view.far_z() as f32],
        ground_blend: sky.sky_fog_ground_blend.uniform().clamp(0.0, 1.0),
        horizon_blend: sky.sky_horizon_fog_blend.uniform().clamp(0.0, 1.0),
    }
}

/// `color` in linear sRGB components through a gamma of 2.2, premultiplied by
/// its alpha times `opacity`.
fn linear(color: &Color, opacity: f32) -> [f32; 4] {
    let [r, g, b, a] = color.to_srgb();
    let alpha = a * opacity;
    if alpha <= 0.0 {
        return [0.0; 4];
    }
    [r.powf(2.2) * alpha, g.powf(2.2) * alpha, b.powf(2.2) * alpha, alpha]
}

#[cfg(test)]
mod tests {
    use approx::assert_abs_diff_eq;
    use mln_style::geo::LatLng;
    use mln_style::property::evaluated::Evaluated;
    use mln_style::size::Size;
    use mln_style::types::ProjectionDefinition;

    use super::*;
    use crate::camera::TransformState;

    /// A sky of a translucent orange fog that starts halfway through the
    /// depth, toward a blue horizon from 0.8.
    fn sky() -> EvaluatedSky {
        EvaluatedSky {
            sky_fog_color: Evaluated::Constant(Color::rgba(1.0, 0.5, 0.0, 0.5)),
            sky_horizon_color: Evaluated::Constant(Color::rgba(0.0, 0.0, 1.0, 1.0)),
            sky_fog_ground_blend: Evaluated::Constant(0.5),
            sky_horizon_fog_blend: Evaluated::Constant(0.8),
            ..EvaluatedSky::default()
        }
    }

    /// A view of terrain pitched `pitch` degrees, its center 1 km up.
    fn pitched(pitch: f64) -> TransformState {
        let mut state = TransformState::default();
        state.set_size(Size::new(512, 384));
        state.set_lat_lng_zoom(&LatLng::new(46.5, 7.9).unwrap(), 12.0);
        state.set_center_altitude(1000.0);
        state.set_pitch(pitch.to_radians());
        state.set_terrain_min_elevation(Some(500.0));
        state
    }

    /// The fog fades in from 60° to 70° of pitch, and out as the view turns
    /// to the globe; there is none without a sky.
    #[test]
    fn the_fog_fades_in_with_the_pitch_and_out_toward_the_globe() {
        let between = |transition| ProjectionDefinition::between_names("mercator", "vertical-perspective", transition);
        let cases = [
            (Some(sky()), 30.0, ProjectionDefinition::default(), None),
            (Some(sky()), 60.0, ProjectionDefinition::default(), None),
            (Some(sky()), 65.0, ProjectionDefinition::default(), Some(0.5)),
            (Some(sky()), 70.0, ProjectionDefinition::default(), Some(1.0)),
            (Some(sky()), 85.0, ProjectionDefinition::default(), Some(1.0)),
            (Some(sky()), 85.0, between(0.25), Some(0.75)),
            (Some(sky()), 85.0, ProjectionDefinition::from_name("vertical-perspective"), None),
            (None, 85.0, ProjectionDefinition::default(), None),
        ];
        for (sky, pitch, projection, expected) in cases {
            let mut state = pitched(pitch);
            state.set_projection(projection.into());
            let fog = terrain_fog(sky.as_ref(), state.view());
            match expected {
                Some(opacity) => assert_abs_diff_eq!(fog.horizon_color[3], opacity, epsilon = 1e-6),
                None => assert_eq!(TerrainFog::NONE, fog, "pitch {pitch}, {projection:?}"),
            }
        }
    }

    /// A transparent fog color has no color, rather than the NaNs of
    /// unpremultiplying it.
    #[test]
    fn a_transparent_fog_color_has_no_color() {
        let sky = EvaluatedSky { sky_fog_color: Evaluated::Constant(Color::default()), ..sky() };
        assert_eq!([0.0; 4], terrain_fog(Some(&sky), pitched(75.0).view()).fog_color);
    }

    /// The blends are clamped to 0..=1, since the style's sky passes on
    /// whatever its expressions evaluate to.
    #[test]
    fn the_blends_are_clamped_to_0_and_1() {
        let sky = EvaluatedSky {
            sky_fog_ground_blend: Evaluated::Constant(-0.5),
            sky_horizon_fog_blend: Evaluated::Constant(1.5),
            ..sky()
        };
        let fog = terrain_fog(Some(&sky), pitched(75.0).view());
        assert_eq!((0.0, 1.0), (fog.ground_blend, fog.horizon_blend));
    }
}