mln-rs-engine 0.0.19

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. 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
// The terrain's drapes: the projection that draws a tile's square of the map
// into its drape, its stencil, the frame's tiles and image copies a drape
// draws, and the drapes that hold a texture.

use std::collections::BTreeSet;
use std::sync::Arc;
use std::time::Duration;

use glam::DVec4;
use mln_gfx::ScissorRect;
use mln_gfx::frame::FrameTarget;
use mln_gfx::offscreen_target::OffscreenTarget;
use mln_style::bitmap::PremultipliedImage;
use mln_style::constants::EXTENT;
use mln_style::geo::LatLng;
use mln_style::size::Size;
use mln_style::subdivision_granularity::SubdivisionGranularitySetting;
use mln_style::tile_id::CanonicalTileID;
use mln_style::{Edit, Style};

use super::fake_gpu::FakeGpu;
use super::with_context;
use crate::camera::transform::Transform;
use crate::camera::{CameraOptions, ConstrainMode, Elevation, View, ViewportMode};
use crate::layer::render_layer::FrameSourceTiles;
use crate::map::{MapMode, TerrainOptions};
use crate::render::clip_masks::ClipMasks;
use crate::render::frame::Frame;
use crate::render::layer_composite::LayerComposite;
use crate::render::paint_parameters::{PaintParameters, TransformParameters};
use crate::render::terrain::Drapes;
use crate::render::tile::{FoundTile, RenderTile, overlaps};
use crate::render::update_parameters::UpdateParameters;
use crate::storage::{FileSource, Resource, Responder, Response};
use crate::tile::{OverscaledTileID, UnwrappedTileID};
use crate::tile_store::TileLodMode;
use crate::{RenderMode, Renderer, RendererEvent, RendererEvents};

/// A camera pitched by `pitch` and turned to `bearing`, in degrees, over a
/// 512 px view at a fractional zoom.
fn view(pitch: f64, bearing: f64) -> View {
    let mut transform = Transform::new(ConstrainMode::HeightOnly, ViewportMode::Default);
    transform.resize(Size::new(512, 512)).unwrap();
    transform.jump_to(&CameraOptions {
        center: Some(LatLng::new(30.0, 20.0).unwrap()),
        zoom: Some(3.7),
        pitch: Some(pitch),
        bearing: Some(bearing),
        ..Default::default()
    });
    transform.view().clone()
}

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

/// Where `transform` draws the point `x`, `y` of `tile`, in clip
/// coordinates.
fn clip(transform: &TransformParameters, tile: UnwrappedTileID, x: f64, y: f64) -> DVec4 {
    transform.proj_matrix * transform.view.tile_matrix(&tile) * DVec4::new(x, y, 0.0, 1.0)
}

#[track_caller]
fn assert_clip(actual: DVec4, x: f64, y: f64) {
    let expected = DVec4::new(x, y, 0.0, 1.0);
    assert!((actual - expected).abs().max_element() < 1e-9, "{actual} is not {expected}");
}

/// A drape draws its tile over the whole target, north up, whatever the
/// camera's pitch and bearing: its parent over four times the target, its
/// children over a quarter, each where it lies, and the tile in another
/// world copy beside it.
#[test]
fn a_drape_projects_its_tile_onto_the_whole_target() {
    let extent = f64::from(EXTENT);
    let view = view(60.0, 30.0);
    let drape = tile(1, 3, 5, 2);
    let transform = TransformParameters::for_drape(&view, &drape);
    assert_clip(clip(&transform, drape, 0.0, 0.0), -1.0, 1.0);
    assert_clip(clip(&transform, drape, extent, extent), 1.0, -1.0);
    assert_clip(clip(&transform, drape, extent / 2.0, extent / 4.0), 0.0, 0.5);

    // The drape's tile is the parent's north-east quarter.
    let parent = tile(1, 2, 2, 1);
    assert_clip(clip(&transform, parent, 0.0, 0.0), -3.0, 1.0);
    assert_clip(clip(&transform, parent, extent, extent), 1.0, -3.0);

    // This child is the drape's south-west quarter.
    let child = tile(1, 4, 10, 5);
    assert_clip(clip(&transform, child, 0.0, 0.0), -1.0, 0.0);
    assert_clip(clip(&transform, child, extent, extent), 0.0, -1.0);

    // The world copy to the west is eight tiles to the west.
    assert_clip(clip(&transform, tile(0, 3, 5, 2), 0.0, 0.0), -17.0, 1.0);
}

/// Where a pass clears the stencil only as it begins, a drape clears it by
/// drawing the mask of a tile that covers its whole target, also in another
/// world copy than the first: its own tile.
#[test]
fn a_drape_clears_its_stencil_over_its_whole_target() {
    with_context(|_, context| {
        let view = view(0.0, 0.0);
        let frame = Frame::new(&view, false);
        let (mut clip_masks, mut layer_composite) = (ClipMasks::default(), LayerComposite::default());
        let size = mln_gfx::Size::new(512, 512);
        let scissor = ScissorRect { x: 0, y: 0, width: size.width, height: size.height };
        let mut parameters =
            PaintParameters::new(context, &mut clip_masks, &mut layer_composite, false, &frame, 1.0, size, scissor);
        assert!(!parameters.context.caps().clear_stencil_with_pass);
        let drape = tile(1, 3, 5, 2);
        let transform = TransformParameters::for_drape(&view, &drape);
        let (mut drape_masks, mut drape_composite) = (ClipMasks::default(), LayerComposite::default());
        let drape_parameters =
            parameters.drape(&transform, &mut drape_masks, &mut drape_composite, mln_gfx::Size::new(1024, 1024), drape);
        let [clear] = drape_parameters.stencil_clear_tiles(&[drape])[..] else {
            panic!("one tile that clears the stencil");
        };
        let extent = f64::from(EXTENT);
        let (north_west, south_east) = (clip(&transform, clear, 0.0, 0.0), clip(&transform, clear, extent, extent));
        let covers = |corner: DVec4, x: f64, y: f64| corner.x * x >= 1.0 - 1e-9 && corner.y * y >= 1.0 - 1e-9;
        assert!(covers(north_west, -1.0, 1.0), "{clear:?}: {north_west}");
        assert!(covers(south_east, 1.0, -1.0), "{clear:?}: {south_east}");
    });
}

/// A drape draws the frame's tiles that overlap its tile, those of its world
/// copy: its own, its ancestors and its descendants, and no others.
#[test]
fn a_drape_draws_the_tiles_that_overlap_its_tile() {
    let ids = [
        tile(0, 3, 5, 2),  // the drape's tile
        tile(0, 2, 2, 1),  // its parent
        tile(0, 0, 0, 0),  // the world's
        tile(0, 5, 21, 9), // a descendant
        tile(0, 3, 4, 2),  // a neighbor
        tile(0, 4, 8, 4),  // the neighbor's child
        tile(0, 2, 3, 1),  // a cousin
        tile(1, 3, 5, 2),  // the drape's tile in the next world copy
    ];
    let render_tiles: Vec<RenderTile> =
        ids.iter().map(|id| RenderTile::of_tile_id(*id, id.overscale_to(id.canonical.z), false)).collect();
    let contents = vec![None; render_tiles.len()];
    let found: Vec<FoundTile> = (0..render_tiles.len()).map(|tile| FoundTile { tile, view: None }).collect();
    let source = FrameSourceTiles::new(&render_tiles, &contents, &found);
    let drawn: Vec<UnwrappedTileID> = source
        .overlapping::<crate::tests::types::layers::TestRaster>(0..found.len(), "raster", ids[0], false)
        .iter()
        .map(|tile| tile.tile.id)
        .collect();
    assert_eq!(&ids[..4], &drawn[..]);
}

/// On the globe, which has no world copies, a drape draws the tiles over
/// its tile whatever their copy: near the antimeridian, a zoom 0 drape in
/// copy 0 draws the western zoom 1 tile that the globe's cover puts in
/// copy 1, as its west half. A Mercator drape doesn't.
#[test]
fn a_globe_drape_draws_the_tiles_over_it_of_every_world_copy() {
    let ids = [tile(1, 1, 0, 0), tile(0, 1, 1, 0), tile(1, 2, 0, 1)];
    let render_tiles: Vec<RenderTile> =
        ids.iter().map(|id| RenderTile::of_tile_id(*id, id.overscale_to(id.canonical.z), false)).collect();
    let contents = vec![None; render_tiles.len()];
    let found: Vec<FoundTile> = (0..render_tiles.len()).map(|tile| FoundTile { tile, view: None }).collect();
    let source = FrameSourceTiles::new(&render_tiles, &contents, &found);
    let drape = tile(0, 0, 0, 0);
    let drawn = |globe: bool| -> Vec<UnwrappedTileID> {
        source
            .overlapping::<crate::tests::types::layers::TestRaster>(0..found.len(), "raster", drape, globe)
            .iter()
            .map(|tile| tile.tile.id)
            .collect()
    };
    assert_eq!(ids.to_vec(), drawn(true));
    assert_eq!(ids[1..2].to_vec(), drawn(false));
}

/// Each copy of an image overlaps the drapes of its own world copy.
#[test]
fn an_image_copy_overlaps_the_drapes_of_its_world_copy() {
    let copies = [tile(0, 3, 5, 2), tile(-1, 3, 5, 2)];
    // The box of the image's quad, in its tile's units.
    let image = [1000, 1000, 7000, 7000];
    assert!(overlaps(&copies[0], image, &tile(0, 3, 5, 2)));
    assert!(!overlaps(&copies[0], image, &tile(-1, 3, 5, 2)));
    assert!(overlaps(&copies[1], image, &tile(-1, 3, 5, 2)));
    assert!(!overlaps(&copies[1], image, &tile(0, 3, 5, 2)));
}

/// An image that reaches past its tile overlaps the drapes of the
/// neighbors it reaches into, and not those of the neighbors it only
/// touches.
#[test]
fn an_image_overlaps_the_drapes_past_its_tile_that_it_reaches() {
    let copies = [tile(0, 3, 5, 2)];
    // From the tile's west half to a quarter into its eastern neighbor, and
    // down to its southern neighbor's edge.
    // The box of the image's quad, in its tile's units.
    let image = [EXTENT / 2, 0, EXTENT + EXTENT / 4, EXTENT];
    assert!(overlaps(&copies[0], image, &tile(0, 3, 5, 2)));
    assert!(overlaps(&copies[0], image, &tile(0, 3, 6, 2)));
    assert!(!overlaps(&copies[0], image, &tile(0, 3, 4, 2)));
    assert!(!overlaps(&copies[0], image, &tile(0, 3, 5, 3)));
    assert!(!overlaps(&copies[0], image, &tile(0, 3, 5, 1)));
    // An image west of its tile, in the next world copy's westernmost tile,
    // reaches into this copy's easternmost.
    let copies = [tile(1, 3, 0, 2)];
    // The box of the image's quad, in its tile's units.
    let image = [-EXTENT / 4, 0, EXTENT / 4, EXTENT];
    assert!(overlaps(&copies[0], image, &tile(0, 3, 7, 2)));
    assert!(overlaps(&copies[0], image, &tile(1, 3, 0, 2)));
    assert!(!overlaps(&copies[0], image, &tile(1, 3, 7, 2)));
}

/// An image overlaps the drapes of coarser tiles that hold part of it, and
/// of finer tiles that it covers part of.
#[test]
fn an_image_overlaps_the_drapes_at_coarser_and_finer_zooms() {
    let copies = [tile(0, 3, 5, 2)];
    // The tile's north-east quarter, and a sliver past its east edge.
    // The box of the image's quad, in its tile's units.
    let image = [EXTENT / 2, 0, EXTENT + 8, EXTENT / 2];
    // Its parent and the world hold it; so does the parent's eastern
    // neighbor, which the sliver reaches.
    assert!(overlaps(&copies[0], image, &tile(0, 2, 2, 1)));
    assert!(overlaps(&copies[0], image, &tile(0, 0, 0, 0)));
    assert!(overlaps(&copies[0], image, &tile(0, 2, 3, 1)));
    assert!(!overlaps(&copies[0], image, &tile(0, 2, 2, 0)));
    // Of the tile's children, only the north-east one; of the eastern
    // neighbor's, only the north-west one, which the sliver reaches.
    assert!(overlaps(&copies[0], image, &tile(0, 4, 11, 4)));
    assert!(!overlaps(&copies[0], image, &tile(0, 4, 10, 4)));
    assert!(!overlaps(&copies[0], image, &tile(0, 4, 11, 5)));
    assert!(overlaps(&copies[0], image, &tile(0, 4, 12, 4)));
    assert!(!overlaps(&copies[0], image, &tile(0, 4, 12, 5)));
    // At zoom 10, the sliver is the first of eight columns of the eastern
    // neighbor's tiles.
    assert!(overlaps(&copies[0], image, &tile(0, 10, 6 * 128, 2 * 128)));
    assert!(!overlaps(&copies[0], image, &tile(0, 10, 6 * 128 + 1, 2 * 128)));
}

/// Answers every request at once with a PNG of sea level in the Mapbox
/// encoding, (1 · 65536 + 134 · 256 + 160) · 0.1 − 10000 = 0 m, which a
/// raster source draws as an opaque color.
struct SeaLevel;

impl FileSource for SeaLevel {
    fn load(&self, _resource: &Resource, responder: Responder) {
        let mut image = PremultipliedImage::new(Size::new(256, 256));
        for texel in image.data.as_chunks_mut::<4>().0 {
            *texel = [1, 134, 160, 255];
        }
        let mut response = Response::new();
        response.data = Some(Arc::new(crate::image::encode_png(&image)));
        responder.send(response);
    }

    fn can_request(&self, _resource: &Resource) -> bool {
        true
    }
}

/// A style over a terrain of flat ground with two raster layers that a
/// circle splits into two stacks: the first of a source whose bounds are in
/// the north-west terrain tile of a view of zoom 2 over 10° E, 10° S, the
/// second in the south-east one.
const TWO_STACKS: &str = r#"{
    "version": 8,
    "terrain": {"source": "dem"},
    "sources": {
        "dem": {"type": "raster-dem", "tiles": ["dem/{z}/{x}/{y}.png"], "tileSize": 256, "maxzoom": 10},
        "north-west": {"type": "raster", "tiles": ["a/{z}/{x}/{y}.png"], "bounds": [-20, 10, -10, 20]},
        "south-east": {"type": "raster", "tiles": ["b/{z}/{x}/{y}.png"], "bounds": [20, -30, 30, -20]},
        "point": {"type": "geojson", "data": {"type": "Point", "coordinates": [10, -10]}}
    },
    "layers": [
        {"id": "north-west", "type": "raster", "source": "north-west", "paint": {"raster-fade-duration": 0}},
        {"id": "circle", "type": "circle", "source": "point"},
        {"id": "south-east", "type": "raster", "source": "south-east", "paint": {"raster-fade-duration": 0}}
    ]
}"#;

/// A style over a terrain of flat ground with a raster layer of a source
/// whose one tile covers the world, under every drape of a view of zoom 2.
const ONE_TILE_UNDER_EVERY_DRAPE: &str = r#"{
    "version": 8,
    "terrain": {"source": "dem"},
    "sources": {
        "dem": {"type": "raster-dem", "tiles": ["dem/{z}/{x}/{y}.png"], "tileSize": 256, "maxzoom": 10},
        "world": {"type": "raster", "tiles": ["a/{z}/{x}/{y}.png"], "maxzoom": 0}
    },
    "layers": [{"id": "world", "type": "raster", "source": "world", "paint": {"raster-fade-duration": 0}}]
}"#;

/// The tile and stack of each drape of a map of `style` that has a texture
/// ([`drapes_of`]).
fn textured_drapes(style: &str) -> BTreeSet<(OverscaledTileID, usize)> {
    drapes_of(style, |drapes| drapes.textured().into_iter().collect())
}

/// A continuous map of `style` at zoom 2 over 10° E, 10° S, seen from above
/// over a 256 px target, drawn until a frame of the camera on the terrain's
/// ground is complete. Returns what `read` reads of its drapes then.
fn drapes_of<R>(style: &str, read: impl FnOnce(&Drapes) -> R) -> R {
    let registry = crate::tests::registry();
    let parsed = Style::from_json(registry.style(), style).expect("the style");
    let mut style = Style::new(Arc::clone(registry.style()));
    for source in parsed.get_sources().iter() {
        style.apply(Edit::AddSource(crate::tests::ready(source.clone()))).unwrap();
    }
    for layer in parsed.get_layer_list().iter() {
        style.apply(Edit::AddLayer { layer: layer.clone(), before: None }).unwrap();
    }
    style.apply(Edit::SetTerrain(parsed.get_terrain().map(|terrain| (**terrain).clone()))).unwrap();
    let style = Arc::new(style);

    let size = Size::new(256, 256);
    let mut gpu = FakeGpu::default();
    let mut target = OffscreenTarget::<FakeGpu>::new(mln_gfx::Size::new(size.width, size.height));
    let pool = crate::tests::pool();
    let mut renderer = Renderer::new(
        &gpu,
        1.0,
        crate::text::local_fonts::LocalGlyphs::default(),
        crate::tests::registry(),
        Arc::new(|| {}),
        &pool,
    );
    let events = RendererEvents::new();
    renderer.set_event_queue(Some(events.clone()));
    let mut transform = Transform::new(ConstrainMode::HeightOnly, ViewportMode::Default);
    transform.resize(size).unwrap();
    transform.jump_to(&CameraOptions {
        center: Some(LatLng::new(-10.0, 10.0).unwrap()),
        zoom: Some(2.0),
        ..Default::default()
    });
    let file_source: Arc<dyn FileSource> = Arc::new(SeaLevel);
    let mut elevation: Option<Arc<dyn Elevation>> = None;
    let mut complete = false;
    for _ in 0..1000 {
        let parameters = Arc::new(UpdateParameters {
            style_loaded: true,
            mode: MapMode::Continuous,
            pixel_ratio: 1.0,
            time_point: None,
            view: transform.view().clone(),
            min_zoom: 0.0,
            max_zoom: 22.0,
            camera_moving: false,
            style: Arc::clone(&style),
            font_faces: None,
            sprite_loaded: true,
            feature_states: Arc::default(),
            file_source: Some(Arc::clone(&file_source)),
            prefetch_zoom_delta: 0,
            still_image_request: false,
            still_image_request_id: 0,
            update_id: 0,
            cross_source_collisions: true,
            fast_pfor_enabled: false,
            terrain: TerrainOptions::default(),
            elevation: elevation.clone(),
            tile_lod_min_radius: 3.0,
            tile_lod_scale: 1.0,
            tile_lod_pitch_threshold: mln_style::math::deg2rad(60.0),
            tile_lod_zoom_shift: 0.0,
            tile_lod_mode: TileLodMode::Default,
            subdivision_granularity: SubdivisionGranularitySetting::none(),
        });
        let frame = renderer.update(&mut gpu, &parameters).expect("a continuous map's frame");
        let image = target.begin_frame(&mut gpu).expect("the frame's image");
        let drawn = renderer.render(&mut gpu, &image, frame);
        let handoff = target.end_frame(&mut gpu);
        renderer.finish_frame(&mut gpu, drawn, handoff);
        for event in events.take() {
            match event {
                RendererEvent::RenderFrameFinished { mode, .. } => complete = mode == RenderMode::Full,
                RendererEvent::TerrainElevation(ground) => elevation = ground,
                _ => {}
            }
        }
        if complete {
            break;
        }
        std::thread::sleep(Duration::from_millis(1));
    }
    assert!(complete, "no frame was complete");
    let read = read(renderer.terrain().drapes());
    target.tear_down(&mut gpu);
    read
}

/// A stack has a drape with a texture only in the terrain tiles where its
/// layers draw something: each raster's stack, only in the tile of its
/// source's bounds.
#[test]
fn a_stack_has_a_drape_texture_only_where_its_layers_draw() {
    let tile = |x, y| OverscaledTileID::new(2, 0, CanonicalTileID::new(2, x, y));
    let expected = BTreeSet::from([(tile(1, 1), 0), (tile(2, 2), 1)]);
    assert_eq!(expected, textured_drapes(TWO_STACKS));
}

/// The drapes that a tile overlaps draw its one value: each draws the same
/// mesh of the world's one raster tile.
#[test]
fn the_drapes_a_tile_overlaps_draw_its_one_value() {
    let meshes = drapes_of(ONE_TILE_UNDER_EVERY_DRAPE, |drapes| drapes.meshes(0));
    assert!(meshes.len() > 1, "the tile under more than one drape: {meshes:?}");
    let first = meshes[0].1.clone();
    assert_eq!(1, first.len(), "one draw of the tile in each drape: {meshes:?}");
    for (tile, drawn) in &meshes {
        assert_eq!(&first, drawn, "the drape of {tile:?} draws another mesh");
    }
}