Skip to main content

mln_engine/draw/
projection.rs

1//! Where a layer's draws of a tile put its geometry, worked out on the CPU as
2//! the shaders work it out: the tile's [`ProjectionData`] in a frame
3//! ([`tile_projection`]), the block that programs read it from
4//! ([`ProjectionData::ubo`]), the scale of extrusions on the globe
5//! ([`globe_extrude_scale`]), and the clip depth of 3D layers on OpenGL
6//! ([`zero_to_one_clip_z`]).
7
8use glam::{DMat4, DVec2, DVec3, Vec2};
9use mln_gfx::shaders::layer_ubo::ProjectionUBO;
10use mln_style::constants::EXTENT;
11use mln_style::types::TranslateAnchorType;
12
13pub use crate::camera::ProjectionData;
14use crate::camera::View;
15use crate::draw::draws::LayerFrame;
16use crate::geo::constants::M2PI;
17use crate::render::paint_parameters::TransformParameters;
18use crate::render::tile::RenderTile;
19use crate::tile::UnwrappedTileID;
20
21/// How a draw places a tile's geometry: moved by a layer's translate
22/// property, and projected with one of the frame's projection matrices.
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct TileTransform {
25    /// The pixels the geometry moves by (a `*-translate` property), along
26    /// the axes that `anchor` says (its `*-translate-anchor`).
27    pub translate: [f32; 2],
28    pub anchor: TranslateAnchorType,
29    /// Projects with the matrix whose near plane is further out, for the
30    /// depth precision of 3D layers.
31    pub near_clipped: bool,
32    /// Projects with the matrix that aligns the tile to whole pixels, for
33    /// crisp images while the camera stands still. It wins over
34    /// `near_clipped`.
35    pub pixel_aligned: bool,
36}
37
38impl TileTransform {
39    /// The tile as it is, projected with the frame's matrix.
40    pub const NONE: TileTransform = TileTransform {
41        translate: [0.0, 0.0],
42        anchor: TranslateAnchorType::Viewport,
43        near_clipped: false,
44        pixel_aligned: false,
45    };
46}
47
48impl Default for TileTransform {
49    fn default() -> Self {
50        TileTransform::NONE
51    }
52}
53
54/// The projection of the tile `tile_id` in `frame`, with its geometry placed
55/// as `transform` says.
56#[must_use]
57pub fn tile_projection(tile_id: &UnwrappedTileID, frame: &LayerFrame<'_>, transform: TileTransform) -> ProjectionData {
58    let matrix = tile_matrix(tile_id, frame.view, frame.transform_params, &transform);
59    let mut data = frame.view.projection_data_for_matrix(tile_id, &matrix);
60    let translate = RenderTile::tile_unit_translation(tile_id, transform.translate, transform.anchor, frame.view);
61    data.translate = DVec2::new(f64::from(translate[0]), f64::from(translate[1]));
62    // A draw's depth range keeps the layers apart, so the shader's depth
63    // offset stays 0.
64    data
65}
66
67impl ProjectionData {
68    /// The block that a program reads the projection from.
69    #[must_use]
70    pub fn ubo(&self) -> ProjectionUBO {
71        // The anchor's offset goes into the matrix in f64, where the camera's
72        // large translation cancels it exactly; the anchor is zero on
73        // Mercator.
74        let anchor = self.sphere_anchor;
75        let plane = self.clipping_plane;
76        ProjectionUBO {
77            matrix: cast_matrix(&(self.main_matrix * DMat4::from_translation(anchor))),
78            fallback_matrix: cast_matrix(&self.fallback_matrix),
79            tile_mercator_coords: self.tile_mercator_coords.as_vec4().to_array(),
80            clipping_plane: self.clipping_plane.as_vec4().to_array(),
81            projection_transition: self.projection_transition as f32,
82            depth_offset: self.depth_offset as f32,
83            translate: self.translate.as_vec2().to_array(),
84            anchor: anchor.extend(anchor.dot(plane.truncate()) + plane.w).as_vec4().to_array(),
85            anchor_angles: self.sphere_anchor_angles.as_vec4().to_array(),
86        }
87    }
88}
89
90/// The radians of the sphere that a pixel of what is aligned with the map
91/// spans on the globe in `view`, for the draws of `tile_id`, which extrude
92/// it there from its center: the same everywhere on the globe, at the
93/// center's scale ([`Projection::map_aligned_scale`]).
94///
95/// [`Projection::map_aligned_scale`]: crate::camera::Projection::map_aligned_scale
96#[must_use]
97pub fn globe_extrude_scale(view: &View, tile_id: &UnwrappedTileID) -> f32 {
98    (f64::from(tile_id.pixels_to_tile_units(1.0, view.zoom() as f32))
99        / (f64::from(EXTENT) * (1u64 << tile_id.canonical.z) as f64)
100        * M2PI
101        * view.projection().map_aligned_scale(view)) as f32
102}
103
104/// Makes a 3D layer's OpenGL matrix clip and write depth as Metal, Vulkan,
105/// D3D12 and WebGPU do with it: clip z from -w to w becomes `2z - w`, so that
106/// OpenGL clips what was below 0 and writes the depth range times the old z
107/// over w.
108pub fn zero_to_one_clip_z(matrix: &mut DMat4) {
109    matrix.set_row(2, 2.0 * matrix.row(2) - matrix.row(3));
110}
111
112/// The matrix that draws geometry of the tile `tile_id` in `view`, placed
113/// as `transform` says, projected with the matrices of `transform_params`.
114fn tile_matrix(
115    tile_id: &UnwrappedTileID,
116    view: &View,
117    transform_params: &TransformParameters,
118    transform: &TileTransform,
119) -> DMat4 {
120    // The near-clipped matrix moves the near plane further out, for the
121    // depth buffer's precision.
122    let projection = if transform.pixel_aligned {
123        &transform_params.aligned_proj_matrix
124    } else if transform.near_clipped {
125        &transform_params.near_clipped_proj_matrix
126    } else {
127        &transform_params.proj_matrix
128    };
129    let matrix = *projection * view.tile_matrix(tile_id);
130    let [x, y] = transform.translate;
131    if x == 0.0 && y == 0.0 {
132        return matrix;
133    }
134    let angle = if transform.anchor == TranslateAnchorType::Viewport { (-view.angle()) as f32 } else { 0.0 };
135    let translate = Vec2::from_angle(angle).rotate(Vec2::new(x, y));
136    let zoom = view.zoom() as f32;
137    let offset = DVec3::new(
138        f64::from(tile_id.pixels_to_tile_units(translate.x, zoom)),
139        f64::from(tile_id.pixels_to_tile_units(translate.y, zoom)),
140        0.0,
141    );
142    matrix * DMat4::from_translation(offset)
143}
144
145/// `m` as the column-major `f32`s that a block's matrix holds.
146fn cast_matrix(m: &DMat4) -> [f32; 16] {
147    m.as_mat4().to_cols_array()
148}