mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::f64::consts::PI;

use glam::{DMat3, DMat4, DVec3};
use mln_gfx::color_mode::ColorMode;
use mln_gfx::cull_face_mode::CullFaceMode;
use mln_gfx::gpu::{Gpu, ShaderKey};
use mln_gfx::projection_variant::ProjectionVariant;
use mln_gfx::{AttributeDataType, DepthMaskType, DrawMode};
use mln_style::color::Color;
use mln_style::geo::WrapMode;
use mln_style::types::LightAnchorType;

use crate::camera::View;
use crate::draw::context::Context;
use crate::draw::draws::{Depth, Draw, SingleDraw};
use crate::draw::indexes::DrawIndexes;
use crate::draw::objects::{DrawGeometry, Mesh, Textures, raw_vertices};
use crate::draw::range::DrawRange;
use crate::draw::vertex_attribute::Uniforms;
use crate::render::light::EvaluatedLight;
use crate::render::paint_parameters::PaintParameters;
use crate::render::sky::EvaluatedSky;
use crate::render::static_data::RenderStaticData;
use crate::shaders::programs;
use crate::shaders::ubo::{AtmospherePropsUBO, SkyPropsUBO};

/// A draw of `shader`, which reads the view's corners as the vertex attribute
/// `vertex_attribute`, in the translucent pass at `depth`.
fn fullscreen_draw(
    context: &mut Context,
    shader: ShaderKey,
    vertex_attribute: &'static str,
    depth: Depth,
) -> SingleDraw {
    let corners: [[i16; 2]; 4] = [[-1, -1], [1, -1], [-1, 1], [1, 1]];
    let vertices = bytemuck::cast_slice(&corners).to_vec();
    let geometry = DrawGeometry {
        vertices: raw_vertices(vertex_attribute, vertices, corners.len(), AttributeDataType::Short2),
        vertex_count: corners.len(),
        mode: DrawMode::Triangles(),
        indexes: DrawIndexes::new(RenderStaticData::quad_triangle_indices()),
        ranges: vec![DrawRange::indexes(6)],
        instances: None,
    };
    let mesh =
        Mesh::new(context, shader, ColorMode::alpha_blended(), CullFaceMode::disabled(), geometry, Textures::default());
    SingleDraw::new(mesh, Draw { depth, ..Draw::DEFAULT })
}

/// The direction of the sun in the globe's frame, where the atmosphere traces
/// its rays (`get_inverse_globe_view_projection_matrix`). A map-anchored light
/// is fixed to the globe, so its direction is already in that frame. A
/// viewport-anchored light is fixed to the view, so it goes back through the
/// globe's rotation into the view, inverted.
fn sun_position(light: &EvaluatedLight, state: &View, blend: f32) -> [f32; 4] {
    let position = light.light_position.uniform().cartesian();
    let mut sun = -DVec3::new(f64::from(position[0]), f64::from(position[1]), f64::from(position[2]));

    if *light.light_anchor.uniform() == LightAnchorType::Viewport {
        let center = state.center(WrapMode::Unwrapped);
        let view_to_globe = DMat3::from_rotation_y(center.longitude() * PI / 180.0)
            * DMat3::from_rotation_x(-center.latitude() * PI / 180.0)
            * DMat3::from_rotation_z(state.angle())
            * DMat3::from_rotation_x(state.pitch())
            * DMat3::from_rotation_z(-state.roll())
            * DMat3::from_rotation_z(state.north_orientation_angle());
        sun = view_to_globe * sun;
    }

    sun.as_vec3().extend(blend).to_array()
}

/// The atmosphere's height in the globe's radii: 100 km over the Earth's.
const ATMOSPHERE_HEIGHT: f64 = 100_000.0 / 6_371_000.0;

/// How much of the atmosphere's glow shows from a camera `altitude` radii
/// above sea level. Seen from inside, the atmosphere is the sky rather than a
/// glow around the planet: none of it shows within its height, and all of it
/// from ten times its height up, eased between.
fn atmosphere_altitude_blend(altitude: f64) -> f64 {
    let x = ((altitude - ATMOSPHERE_HEIGHT) / (9.0 * ATMOSPHERE_HEIGHT)).clamp(0.0, 1.0);
    x * x * (3.0 - 2.0 * x)
}

fn color_components(color: &Color) -> [f32; 4] {
    color.to_premultiplied()
}

/// Owns the source-independent fullscreen passes used by the root `sky` style property.
///
/// The sky is rendered before style layers: above a flat horizon on Mercator,
/// and above the planet's limb on the globe, where it shows only from within
/// the atmosphere. The physical atmosphere is rendered after them, against the
/// globe depth prepass, so the planet correctly occludes it.
#[derive(Default)]
pub(crate) struct SkyPass {
    sky: Option<SingleDraw>,
    atmosphere: Option<SingleDraw>,
}

impl SkyPass {
    pub(crate) fn update(
        &mut self,
        gpu: &mut dyn Gpu,
        parameters: &mut PaintParameters<'_>,
        evaluated: Option<&EvaluatedSky>,
    ) {
        let state = parameters.view;
        let viewport_size = parameters.renderable_size;
        let pixel_ratio = parameters.pixel_ratio;
        let light = parameters.light;
        let context = &mut *parameters.context;

        let Some(evaluated) = evaluated.filter(|_| !viewport_size.is_empty()) else {
            self.sky = None;
            self.atmosphere = None;
            return;
        };

        let projection_transition = state.projection_transition().clamp(0.0, 1.0);
        let globe_camera = state.is_globe().then(|| state.globe_camera_position());
        let atmosphere_blend = *evaluated.sky_atmosphere_blend.uniform()
            * globe_camera.map_or(0.0, |camera| atmosphere_altitude_blend(camera.length() - 1.0)) as f32;

        let sky = self.sky.get_or_insert_with(|| {
            let shader = context.shader_key(&programs::SKY, Uniforms::default(), ProjectionVariant::Mercator);
            let depth = Depth::Layer { sub_layer: 0, mask: DepthMaskType::ReadWrite };
            fullscreen_draw(context, shader, "pos", depth)
        });
        let horizon_distance = state.mercator_horizon() * f64::from(pixel_ratio);
        let roll = state.roll();
        let normal = [(-roll.sin()) as f32, roll.cos() as f32];
        let horizon = [
            (f64::from(viewport_size.width) * 0.5 + f64::from(normal[0]) * horizon_distance) as f32,
            (f64::from(viewport_size.height) * 0.5 + f64::from(normal[1]) * horizon_distance) as f32,
        ];
        // The rays go from the camera, so the matrix moves it to the origin
        // in f64, where the unit sphere's coordinates of the camera and of
        // points a pixel from it would round to the same f32s.
        let (inv_view_projection, globe_center) = match globe_camera {
            Some(camera) => (
                DMat4::from_translation(-camera) * state.inverse_globe_view_projection_matrix(),
                (-camera).as_vec3().extend(0.0),
            ),
            None => (DMat4::IDENTITY, glam::Vec4::ZERO),
        };
        let props = SkyPropsUBO {
            sky_color: color_components(evaluated.sky_color.uniform()),
            horizon_color: color_components(evaluated.sky_horizon_color.uniform()),
            horizon,
            horizon_normal: normal,
            viewport_size: [viewport_size.width as f32, viewport_size.height as f32],
            sky_horizon_blend: *evaluated.sky_horizon_blend.uniform() * viewport_size.height as f32 * 0.5,
            sky_blend: projection_transition as f32,
            inv_view_projection: inv_view_projection.as_mat4().to_cols_array(),
            globe_center: globe_center.to_array(),
            pixels_per_radian: state.camera_to_center_distance() as f32,
            pixel_ratio,
            atmosphere_blend,
            pad0: 0.0,
        };
        sky.block(&props).write(gpu, context, ());

        let atmosphere_blend = atmosphere_blend * projection_transition as f32;
        let Some(camera) = globe_camera.filter(|_| atmosphere_blend > 0.0) else {
            self.atmosphere = None;
            return;
        };

        let atmosphere = self.atmosphere.get_or_insert_with(|| {
            let shader = context.shader_key(&programs::ATMOSPHERE, Uniforms::default(), ProjectionVariant::Globe);
            fullscreen_draw(context, shader, "pos", Depth::Volume { mask: DepthMaskType::ReadOnly })
        });

        let props = AtmospherePropsUBO {
            inv_view_projection: state.inverse_globe_view_projection_matrix().as_mat4().to_cols_array(),
            camera_position: camera.as_vec3().extend(0.0).to_array(),
            sun_position: sun_position(light, state, atmosphere_blend),
        };
        atmosphere.block(&props).write(gpu, context, ());
    }

    /// The sky, which draws before the layers, if the frame draws it.
    #[must_use]
    pub(crate) fn sky(&mut self) -> Option<&mut SingleDraw> {
        self.sky.as_mut()
    }

    /// The globe's atmosphere, which draws after the layers, if the frame
    /// draws it.
    #[must_use]
    pub(crate) fn atmosphere(&mut self) -> Option<&mut SingleDraw> {
        self.atmosphere.as_mut()
    }

    #[must_use]
    pub(crate) fn has_atmosphere(&self) -> bool {
        self.atmosphere.is_some()
    }
}

#[cfg(test)]
mod tests {
    use approx::assert_abs_diff_eq;
    use glam::Vec3;
    use mln_style::geo::LatLng;
    use mln_style::property::evaluated::Evaluated;
    use mln_style::types::Position;

    use super::*;
    use crate::camera::{NorthOrientation, TransformState};

    /// A viewport light at [1.5, 90, 90] stays on the right of the view. With
    /// north down, that is west of the center: seen from 0°N 0°E, over 0°N
    /// 90°W, which is -x in the globe's frame (+x points to 0°N 90°E, +y to
    /// the North Pole and +z to 0°N 0°E).
    #[test]
    fn a_viewport_light_turns_with_the_north_orientation() {
        let light = EvaluatedLight {
            light_anchor: Evaluated::Constant(LightAnchorType::Viewport),
            light_position: Evaluated::Constant(Position::new([1.5, 90.0, 90.0])),
            ..EvaluatedLight::default()
        };
        let mut state = TransformState::default();
        state.set_size(mln_style::size::Size::new(512, 512));
        state.set_lat_lng_zoom(&LatLng::new(0.0, 0.0).unwrap(), 1.0);
        state.set_north_orientation(NorthOrientation::Downwards);
        let sun = Vec3::from_slice(&sun_position(&light, state.view(), 1.0));
        assert_abs_diff_eq!(Vec3::new(-1.5, 0.0, 0.0), sun, epsilon = 1e-5);
    }
}