Skip to main content

mln_engine/render/globe/
globe_tile_mesh.rs

1use std::collections::BTreeMap;
2use std::marker::PhantomData;
3
4use geometry::Point;
5use mln_style::constants::EXTENT;
6use mln_style::subdivision_granularity::{SubdivisionGranularityExpression, SubdivisionGranularitySetting};
7use mln_style::tile_id::CanonicalTileID;
8
9use crate::draw::context::Context;
10use crate::draw::indexes::{DrawIndexes, Indexes, SharedIndexes};
11use crate::draw::mesh::Indexed;
12use crate::draw::segment::SegmentBase;
13use crate::draw::vertices::SharedVertices;
14use crate::render::globe::tile_mesh::{TileMeshOptions, create_tile_mesh};
15use crate::render::globe::{NORTH_POLE_Y, SOUTH_POLE_Y};
16use crate::tile_store::tile_mask::TileMask;
17
18/// The pole-capped globe grid for the parts of a tile its mask keeps, as
19/// position + texture-position vertices, in the context's stores. Each part
20/// is gridded like the tile it stands in for, so it meets that tile's
21/// neighbours edge to edge; texture positions stay inside the tile so the
22/// pole rows sample the tile's edge.
23pub struct GlobeTileMesh {
24    pub vertices: SharedVertices,
25    indices: SharedIndexes,
26    pub segments: Vec<SegmentBase>,
27}
28
29/// The data of a [`GlobeTileMesh`]: its vertices, indices and segments.
30pub(crate) struct GlobeMeshData<V> {
31    pub(crate) vertices: Vec<V>,
32    pub(crate) indices: Vec<u16>,
33    pub(crate) segments: Vec<SegmentBase>,
34}
35
36impl GlobeTileMesh {
37    /// The mesh of the parts of the tile `canonical` that `mask` keeps, of
38    /// `layout_vertex`'s vertices, in `context`'s stores.
39    pub(crate) fn new<V: bytemuck::Pod>(
40        context: &mut Context,
41        canonical: &CanonicalTileID,
42        mask: &TileMask,
43        layout_vertex: fn(Point<i16>, Point<u16>) -> V,
44    ) -> Self {
45        let GlobeMeshData { vertices, indices, segments } = globe_mesh_data(canonical, mask, layout_vertex);
46        GlobeTileMesh {
47            vertices: context.add_vertices(vertices),
48            indices: context.add_indexes(Indexes::new(indices)),
49            segments,
50        }
51    }
52
53    /// The mesh's indexes, for a draw that shares them.
54    #[must_use]
55    pub fn indexes(&self) -> DrawIndexes {
56        DrawIndexes::Shared(self.indices.clone())
57    }
58}
59
60/// The data of the [`GlobeTileMesh`] of the parts of the tile `canonical`
61/// that `mask` keeps, of `layout_vertex`'s vertices.
62pub(crate) fn globe_mesh_data<V: Copy>(
63    canonical: &CanonicalTileID,
64    mask: &TileMask,
65    layout_vertex: fn(Point<i16>, Point<u16>) -> V,
66) -> GlobeMeshData<V> {
67    let mut vertices: Vec<V> = Vec::new();
68    let (mut indices, mut segments) = (Vec::new(), Vec::new());
69    for part in mask {
70        let mesh = create_tile_mesh(TileMeshOptions {
71            granularity: SubdivisionGranularitySetting::globe()
72                .tile
73                .granularity_for_zoom_level(canonical.z.wrapping_add(part.z)),
74            generate_borders: false,
75            extend_to_north_pole: canonical.y == 0 && part.y == 0,
76            extend_to_south_pole: canonical.y == (1u32 << canonical.z) - 1 && part.y == (1u32 << part.z) - 1,
77        });
78        let first = vertices.len();
79        let extent = EXTENT >> part.z;
80        for &[x, y] in &mesh.vertices {
81            let position = Point::new(
82                (part.x as i32 * extent + (i32::from(x) >> part.z)) as i16,
83                if y == NORTH_POLE_Y || y == SOUTH_POLE_Y {
84                    y
85                } else {
86                    (part.y as i32 * extent + (i32::from(y) >> part.z)) as i16
87                },
88            );
89            // Texture positions stay inside the tile.
90            let clamp = |value: i16| i32::from(value).clamp(0, EXTENT) as u16;
91            let texture = Point::new(clamp(position.x), clamp(position.y));
92            vertices.push(layout_vertex(position, texture));
93        }
94        let mut triangles = Indexed { indexes: &mut indices, segments: &mut segments };
95        triangles.add(&mut vertices, first, mesh.triangles.iter().map(|t| t.map(u32::from)));
96    }
97    GlobeMeshData { vertices, indices, segments }
98}
99
100struct Entry {
101    mesh: GlobeTileMesh,
102    last_use: u64,
103}
104
105/// The grids a layer has built so far, one per zoom, pole row and mask: the
106/// mesh depends on nothing else.
107pub struct GlobeTileMeshCache<V: bytemuck::Pod> {
108    uses: u64,
109    meshes: BTreeMap<(u8, bool, bool, TileMask), Entry>,
110    vertex_type: PhantomData<fn() -> V>,
111}
112
113impl<V: bytemuck::Pod> Default for GlobeTileMeshCache<V> {
114    fn default() -> Self {
115        GlobeTileMeshCache { uses: 0, meshes: BTreeMap::new(), vertex_type: PhantomData }
116    }
117}
118
119impl<V: bytemuck::Pod> GlobeTileMeshCache<V> {
120    const MAX_MESHES: usize = 64;
121
122    /// An empty cache.
123    #[must_use]
124    pub fn new() -> Self {
125        Self::default()
126    }
127
128    /// The mesh of the parts of the tile `canonical` that `mask` keeps, of
129    /// `layout_vertex`'s vertices, which `context`'s stores keep.
130    pub fn get(
131        &mut self,
132        context: &mut Context,
133        canonical: &CanonicalTileID,
134        mask: &TileMask,
135        layout_vertex: fn(Point<i16>, Point<u16>) -> V,
136    ) -> &GlobeTileMesh {
137        let key = (canonical.z, canonical.y == 0, canonical.y == (1u32 << canonical.z) - 1, mask.clone());
138        // Tiles that are loading go through many masks; the one used longest
139        // ago makes room, so the meshes every frame draws stay. The draws share
140        // the meshes' buffers, so they keep theirs.
141        if !self.meshes.contains_key(&key)
142            && self.meshes.len() >= Self::MAX_MESHES
143            && let Some(oldest) = self.meshes.iter().min_by_key(|(_, entry)| entry.last_use).map(|(key, _)| key.clone())
144        {
145            self.meshes.remove(&oldest);
146        }
147        self.uses += 1;
148        let entry = self.meshes.entry(key).or_insert_with(|| Entry {
149            mesh: GlobeTileMesh::new(context, canonical, mask, layout_vertex),
150            last_use: 0,
151        });
152        entry.last_use = self.uses;
153        &entry.mesh
154    }
155
156    /// Lets go of every mesh.
157    pub fn clear(&mut self) {
158        self.meshes.clear();
159    }
160
161    #[cfg(test)]
162    #[must_use]
163    pub(crate) fn size(&self) -> usize {
164        self.meshes.len()
165    }
166}
167
168/// The same grid as raw `Short2` positions, for draws built from raw
169/// vertex bytes.
170#[derive(Debug, Default)]
171pub struct RawGlobeTileMesh {
172    pub vertices: Vec<u8>,
173    pub vertex_count: usize,
174    pub indices: Vec<u16>,
175    pub segments: Vec<SegmentBase>,
176}
177
178/// The globe mesh of the tile `canonical`, with borders if
179/// `generate_borders`, subdivided by `granularity`.
180#[must_use]
181pub fn raw_globe_tile_mesh(
182    canonical: &CanonicalTileID,
183    generate_borders: bool,
184    granularity: SubdivisionGranularityExpression,
185) -> RawGlobeTileMesh {
186    let mesh = create_tile_mesh(TileMeshOptions {
187        granularity: granularity.granularity_for_zoom_level(canonical.z),
188        generate_borders,
189        extend_to_north_pole: canonical.y == 0,
190        extend_to_south_pole: canonical.y == (1u32 << canonical.z) - 1,
191    });
192    let vertex_count = mesh.vertices.len();
193    debug_assert!(u16::try_from(vertex_count).is_ok());
194    let index_count = 3 * mesh.triangles.len();
195    RawGlobeTileMesh {
196        vertices: bytemuck::cast_slice(&mesh.vertices).to_vec(),
197        vertex_count,
198        indices: mesh.triangles.into_flattened(),
199        segments: vec![SegmentBase::with_lengths(0, 0, vertex_count, index_count)],
200    }
201}