mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
// A render tile is a tile as a frame draws it: where it draws, its
// matrices, and what it copies of the tile and its render entry (its id,
// hold-for-fade state and whether it draws a visible layer) when the
// frame's update makes it. It lives in its render source, apart from the
// tile store. The frame's phases look the tile's contents up through its
// source, in the store by the tile's slot and id (`TileContent`, `FrameTile`);
// the store changes them only in the frame's update, before the layers read
// them.

use std::time::Duration;

use glam::{DMat4, Vec2};
use mln_style::constants;
use mln_style::types::TranslateAnchorType;

use crate::camera::{ProjectionData, View};
use crate::draw::identity::SimpleIdentity;
use crate::layer::layer_drawing::MadeFrom;
use crate::layer::render_layer::Layer;
use crate::layer::tile_input::TileData;
use crate::layer::tile_input::input::Find;
use crate::render::paint_parameters::TransformParameters;
use crate::render::pass::RenderPass;
use crate::source::render_image_source::ImageTile;
use crate::tile::{OverscaledTileID, UnwrappedTileID};
use crate::tile_store::contents::Contents;
use crate::tile_store::tile::Tile;

/// A tile of a source that the frame draws: its id, its projection, and
/// what of its contents the layers draw.
pub struct RenderTile {
    pub(crate) id: UnwrappedTileID,
    /// The projection contract for this tile; `matrix` is its main matrix.
    pub(crate) projection: ProjectionData,
    pub(crate) matrix: DMat4,

    /// `tile.id`.
    tile_id: OverscaledTileID,
    tile_hold_for_fade: bool,
    /// Where the tile is among its source's, which finds its contents
    /// first; `None` for a tile that isn't among a source's.
    slot: Option<usize>,
    /// How the tile fades, while it does.
    pub(crate) fade: Option<RenderFade>,
    /// Whether the frame has the tile only for another that fades with its
    /// image: no layer draws it.
    pub(crate) fade_parent_only: bool,
}

/// How a render tile fades
/// ([`TileFade`](crate::tile_store::source_tiles::TileFade)), with its
/// parent's index among its source's render tiles.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RenderFade {
    pub(crate) parent: Option<usize>,
    pub(crate) elapsed: Duration,
    pub(crate) fade_in: bool,
}

impl RenderTile {
    /// The render tile of `tile`, at `slot` of its source's tiles, drawn as
    /// `id`, before its first update.
    pub(crate) fn new(id: UnwrappedTileID, tile: &Tile, slot: usize, hold_for_fade: bool) -> Self {
        RenderTile { slot: Some(slot), ..RenderTile::of_tile_id(id, tile.id, hold_for_fade) }
    }

    /// The render tile of the tile `tile_id`, drawn as `id`, before it is
    /// updated, which isn't among a source's tiles.
    pub(crate) fn of_tile_id(id: UnwrappedTileID, tile_id: OverscaledTileID, hold_for_fade: bool) -> Self {
        RenderTile {
            id,
            projection: ProjectionData::default(),
            // `set_projection` sets it.
            matrix: DMat4::ZERO,
            tile_id,
            tile_hold_for_fade: hold_for_fade,
            slot: None,
            fade: None,
            fade_parent_only: false,
        }
    }

    /// The layer's translation in tile units, rotated for its anchor.
    #[must_use]
    pub fn tile_unit_translation(
        id: &UnwrappedTileID,
        translation: [f32; 2],
        anchor: TranslateAnchorType,
        state: &View,
    ) -> [f32; 2] {
        if translation[0] == 0.0 && translation[1] == 0.0 {
            return [0.0, 0.0];
        }
        let angle = if anchor == TranslateAnchorType::Viewport { (-state.angle()) as f32 } else { 0.0f32 };
        let translate = Vec2::from_angle(angle).rotate(Vec2::new(translation[0], translation[1]));
        let zoom = state.zoom() as f32;
        [id.pixels_to_tile_units(translate.x, zoom), id.pixels_to_tile_units(translate.y, zoom)]
    }

    /// The id the tile draws as: its world copy of the tile.
    #[must_use]
    pub fn id(&self) -> UnwrappedTileID {
        self.id
    }

    /// The tile's id.
    #[must_use]
    pub fn overscaled_tile_id(&self) -> &OverscaledTileID {
        &self.tile_id
    }

    /// Where the tile is among its source's, as of its last update; `None`
    /// for a tile that isn't among a source's.
    #[must_use]
    pub fn slot(&self) -> Option<usize> {
        self.slot
    }

    /// Whether the tile stays only while a placement fades its marks out.
    #[must_use]
    pub fn hold_for_fade(&self) -> bool {
        self.tile_hold_for_fade
    }

    /// The tile's projection in the frame.
    #[must_use]
    pub fn projection(&self) -> &ProjectionData {
        &self.projection
    }

    /// The tile's main matrix in the frame: its projection's.
    #[must_use]
    pub fn matrix(&self) -> &DMat4 {
        &self.matrix
    }

    /// Sets the tile's projection and its standard matrix for `transform`.
    pub(crate) fn set_projection(&mut self, transform: &TransformParameters) {
        self.projection = transform.view.projection_data_with(&self.id, &transform.proj_matrix);
        self.matrix = self.projection.main_matrix;
    }
}

/// What a frame's tile shows the layers of its source: its contents in the
/// tile store, or an image source's image, which each of the source's
/// tiles draws.
#[derive(Clone, Copy)]
pub(crate) enum TileContent<'a> {
    Tile(&'a Contents),
    Image(&'a ImageTile),
}

impl TileContent<'_> {
    /// The bucket or the raster, raster-dem or image contents that the
    /// content shows at `place`, with the generations of their mask or mesh
    /// and of their DEM's border.
    pub(crate) fn stamp(self, place: ViewPlace) -> Option<(SimpleIdentity, [u64; 2])> {
        match (self, place) {
            (TileContent::Tile(contents), place) => contents.stamp(place),
            (TileContent::Image(image), ViewPlace::Own) => Some(image.stamp()),
            (TileContent::Image(_), ViewPlace::Laid(_)) => None,
        }
    }

    /// The box that the content draws over, in its tile's units: min x,
    /// min y, max x, max y. A tile's contents draw over the tile; an image
    /// source's image over the box of its quad's corners, which may reach
    /// past the tile.
    pub(crate) fn bounds(self) -> [i32; 4] {
        match self {
            TileContent::Tile(_) => TILE_BOUNDS,
            TileContent::Image(image) => image.bounds,
        }
    }
}

/// The box of a whole tile, in its units.
pub(crate) const TILE_BOUNDS: [i32; 4] = [0, 0, constants::EXTENT, constants::EXTENT];

/// Whether `bounds`, a box in the units of the tile `tile`, covers part of
/// the tile `other`. A box that only touches its edge doesn't.
pub(crate) fn overlaps(tile: &UnwrappedTileID, bounds: [i32; 4], other: &UnwrappedTileID) -> bool {
    // Both boxes in the tile units of the finer of the two zooms, from the
    // west edge of world copy 0.
    let zoom = tile.canonical.z.max(other.canonical.z);
    let place = |id: &UnwrappedTileID| {
        let scale = 1i64 << (zoom - id.canonical.z);
        let extent = i64::from(constants::EXTENT) * scale;
        let x = ((i64::from(id.wrap) << id.canonical.z) + i64::from(id.canonical.x)) * extent;
        (x, i64::from(id.canonical.y) * extent, scale)
    };
    let (left, top, scale) = place(tile);
    let [min_x, min_y, max_x, max_y] = bounds.map(|bound| i64::from(bound) * scale);
    let (other_left, other_top, other_scale) = place(other);
    let other_extent = i64::from(constants::EXTENT) * other_scale;
    left + min_x < other_left + other_extent
        && other_left < left + max_x
        && top + min_y < other_top + other_extent
        && other_top < top + max_y
}

/// Where a tile's contents keep what they show a layer. The frame's found
/// tiles keep it for layers of every type in one list, so a place of one
/// type's inputs can reach another's
/// [`Find::at`](crate::layer::tile_input::input::Find::at), which asserts
/// that it doesn't.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ViewPlace {
    /// The layer's place among the layers of the tile's layout.
    Laid(usize),
    /// The tile's own contents, a raster or raster-dem tile's or an image
    /// source's image, which every layer of its source draws.
    Own,
}

/// What a layer draws of a frame's tile: the tile, the bucket or contents
/// it shows the layer, and the generations of their mask or mesh and of
/// their DEM's border. It changes whenever the layer's draws of the tile
/// would.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct TileStamp {
    pub(crate) tile: OverscaledTileID,
    pub(crate) bucket: Option<SimpleIdentity>,
    pub(crate) generations: [u64; 2],
}

/// A layer's tile of a frame, as the frame's update found it: its index
/// among its source's render tiles, and where what it shows the layer is in
/// its contents ([`Find::find`](crate::layer::tile_input::input::Find::find)).
#[derive(Clone, Copy, Debug)]
pub(crate) struct FoundTile {
    pub(crate) tile: usize,
    pub(crate) view: Option<ViewPlace>,
}

/// A render tile of a frame, with what it holds for a layer of the type
/// `T` and the world copy the layer draws it in.
pub struct FrameTile<'a, T: Layer> {
    pub(crate) tile: &'a RenderTile,
    /// The world copy the layer draws the tile in: its own, but in a drape
    /// one by the drape's.
    wrap: i16,
    data: Option<TileData<'a, T>>,
    fade: Option<TileFade<'a, T>>,
}

/// How a frame's tile fades in, from its parent's image or from nothing,
/// or out to the parent's image, as its parent replaces it, for a layer of
/// the type `T` that fades tiles
/// ([`Layer::tile_fade`](crate::layer::Layer::tile_fade)).
pub struct TileFade<'a, T: Layer> {
    parent: Option<(OverscaledTileID, TileData<'a, T>)>,
    elapsed: Duration,
    fade_in: bool,
}

impl<T: Layer> Clone for TileFade<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: Layer> Copy for TileFade<'_, T> {}

impl<'a, T: Layer> TileFade<'a, T> {
    pub(crate) fn new(parent: Option<(OverscaledTileID, TileData<'a, T>)>, elapsed: Duration, fade_in: bool) -> Self {
        TileFade { parent, elapsed, fade_in }
    }

    /// The loaded tile above the tile, whose image it blends with, and what
    /// that holds for the layer; `None` for a tile that fades in over what
    /// is under it.
    #[must_use]
    pub fn parent(self) -> Option<(OverscaledTileID, TileData<'a, T>)> {
        self.parent
    }

    /// How much of the tile shows at the frame's time, from 0 to 1, for a
    /// layer that fades tiles over `duration`: of its own image rather than
    /// its parent's where it has a parent, and otherwise its opacity.
    #[must_use]
    pub fn shown(self, duration: Duration) -> f32 {
        let done =
            if duration.is_zero() { 1.0 } else { (self.elapsed.as_secs_f32() / duration.as_secs_f32()).min(1.0) };
        if self.fade_in { done } else { 1.0 - done }
    }
}

impl<T: Layer> Clone for FrameTile<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: Layer> Copy for FrameTile<'_, T> {}

impl<'a, T: Layer> FrameTile<'a, T> {
    /// The tile `tile`, which shows `content`, as the layer `layer_id`
    /// sees it, and where it found what the tile holds for the layer.
    #[must_use]
    pub(crate) fn find(
        tile: &'a RenderTile,
        content: Option<TileContent<'a>>,
        layer_id: &str,
    ) -> (Self, Option<ViewPlace>) {
        let found = content.and_then(|content| <T::Input as Find<T::Style>>::find(content, layer_id));
        let frame_tile = FrameTile { tile, wrap: tile.id.wrap, data: found.map(|(data, _)| data), fade: None };
        (frame_tile, found.map(|(_, place)| place))
    }

    /// The tile `tile`, which shows `content`, as the layer `layer_id`
    /// sees it, with what it holds for the layer at `view` in `content`,
    /// where [`find`](Self::find) found it.
    #[must_use]
    pub(crate) fn at(
        tile: &'a RenderTile,
        content: Option<TileContent<'a>>,
        layer_id: &str,
        view: Option<ViewPlace>,
    ) -> Self {
        let data = content.zip(view).and_then(|(content, place)| <T::Input as Find<T::Style>>::at(content, place));
        debug_assert_eq!(data.is_some(), view.is_some(), "a tile's contents changed since the frame's update");
        debug_assert!(
            data.is_none_or(|data| <T::Input as Find<T::Style>>::is_for(data, layer_id)),
            "a layer found at another's place"
        );
        FrameTile { tile, wrap: tile.id.wrap, data, fade: None }
    }

    /// The tile, which fades as `fade` says.
    #[must_use]
    pub(crate) fn with_fade(self, fade: Option<TileFade<'a, T>>) -> Self {
        FrameTile { fade, ..self }
    }

    /// How the tile fades in the map's frame, while it does; never in a
    /// drape.
    #[must_use]
    pub fn fade(self) -> Option<TileFade<'a, T>> {
        self.fade
    }

    /// The tile, drawn in the world copy `wrap`.
    #[must_use]
    pub(crate) fn in_copy(self, wrap: i16) -> Self {
        FrameTile { wrap, ..self }
    }

    /// What the layer's value of the tile is made from, if the tile holds
    /// anything for the layer ([`TileContent::stamp`]).
    pub(crate) fn made_from(self) -> Option<MadeFrom> {
        self.data.map(<T::Input as Find<T::Style>>::made_from)
    }

    /// The tile as the frame draws it.
    #[must_use]
    pub fn render_tile(self) -> &'a RenderTile {
        self.tile
    }

    /// What the tile holds for the layer, if anything.
    pub fn data(self) -> Option<TileData<'a, T>> {
        self.data
    }

    /// [`data`](Self::data), if it was laid out to draw in `pass`.
    pub fn data_for_pass(self, pass: RenderPass) -> Option<TileData<'a, T>> {
        self.data.filter(|&data| <T::Input as Find<T::Style>>::passes(data) & pass != RenderPass::NONE)
    }

    /// The tile's id.
    #[must_use]
    pub fn id(self) -> OverscaledTileID {
        *self.tile.overscaled_tile_id()
    }

    /// The id that the layer draws the tile under: its own, but in a drape
    /// in the world copy the drape draws it in.
    #[must_use]
    pub fn draw_id(self) -> OverscaledTileID {
        OverscaledTileID { wrap: self.wrap, ..self.id() }
    }
}

#[cfg(test)]
mod tests {
    use mln_style::constants::EXTENT;
    use mln_style::tile_id::CanonicalTileID;

    use super::*;

    fn tile(wrap: i16, z: u8, x: u32, y: u32) -> UnwrappedTileID {
        UnwrappedTileID::with_wrap(wrap, CanonicalTileID::new(z, x, y))
    }

    /// A box overlaps the tiles it covers part of, in its tile's world copy:
    /// the neighbors it reaches into, but not those it only touches, and
    /// coarser tiles that hold part of it and finer tiles it covers part of.
    #[test]
    fn a_box_overlaps_the_tiles_it_covers_part_of() {
        let inside = [1000, 1000, 7000, 7000];
        // From the tile's west half to a quarter into its eastern neighbor.
        let east = [EXTENT / 2, 0, EXTENT + EXTENT / 4, EXTENT];
        // West of its tile, in the next world copy's westernmost tile.
        let west = [-EXTENT / 4, 0, EXTENT / 4, EXTENT];
        // The tile's north-east quarter, and a sliver past its east edge.
        let sliver = [EXTENT / 2, 0, EXTENT + 8, EXTENT / 2];
        let cases = [
            // Each world copy of a box overlaps the tiles of its own.
            (tile(0, 3, 5, 2), inside, tile(0, 3, 5, 2), true),
            (tile(0, 3, 5, 2), inside, tile(-1, 3, 5, 2), false),
            (tile(-1, 3, 5, 2), inside, tile(-1, 3, 5, 2), true),
            (tile(-1, 3, 5, 2), inside, tile(0, 3, 5, 2), false),
            (tile(0, 3, 5, 2), east, tile(0, 3, 6, 2), true),
            (tile(0, 3, 5, 2), east, tile(0, 3, 4, 2), false),
            (tile(0, 3, 5, 2), east, tile(0, 3, 5, 3), false),
            (tile(0, 3, 5, 2), east, tile(0, 3, 5, 1), false),
            (tile(1, 3, 0, 2), west, tile(0, 3, 7, 2), true),
            (tile(1, 3, 0, 2), west, tile(1, 3, 0, 2), true),
            (tile(1, 3, 0, 2), west, tile(1, 3, 7, 2), false),
            // The parent and the world hold the sliver's box, and so does
            // the parent's eastern neighbor, which the sliver reaches.
            (tile(0, 3, 5, 2), sliver, tile(0, 2, 2, 1), true),
            (tile(0, 3, 5, 2), sliver, tile(0, 0, 0, 0), true),
            (tile(0, 3, 5, 2), sliver, tile(0, 2, 3, 1), true),
            (tile(0, 3, 5, 2), sliver, tile(0, 2, 2, 0), false),
            // Of the tile's children only the north-east one, and of the
            // eastern neighbor's only the north-west one.
            (tile(0, 3, 5, 2), sliver, tile(0, 4, 11, 4), true),
            (tile(0, 3, 5, 2), sliver, tile(0, 4, 10, 4), false),
            (tile(0, 3, 5, 2), sliver, tile(0, 4, 11, 5), false),
            (tile(0, 3, 5, 2), sliver, tile(0, 4, 12, 4), true),
            (tile(0, 3, 5, 2), sliver, tile(0, 4, 12, 5), false),
            // At zoom 10, the sliver is the first of eight columns of the
            // eastern neighbor's tiles.
            (tile(0, 3, 5, 2), sliver, tile(0, 10, 6 * 128, 2 * 128), true),
            (tile(0, 3, 5, 2), sliver, tile(0, 10, 6 * 128 + 1, 2 * 128), false),
        ];
        for (tile, bounds, other, expected) in cases {
            assert_eq!(expected, overlaps(&tile, bounds, &other), "{bounds:?} of {tile:?} over {other:?}");
        }
    }
}