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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! How the camera stands on the terrain its renderer drew, and how the
//! map's updates carry that ground back to the renderer, which completes a
//! frame only of an update whose camera stands as it would on its newest.

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

use approx::assert_abs_diff_eq;
use glam::DVec2;
use mln_style::Edit;
use mln_style::geo::{LatLng, WrapMode};

use crate::camera::{AnimationOptions, BoundOptions, CameraOptions, CameraUpdate, CameraUpdateMode, Elevation};
use crate::exec::queue::Queue;
use crate::map::{Map, MapEvent, MapMode, MapOptions};
use crate::storage::stub_file_source::{ResponseType, StubFileSource};
use crate::{RenderMode, RendererEvent};

pub(super) const STYLE: &str = r#"{
    "version": 8,
    "center": [10, 20],
    "zoom": 3,
    "terrain": {"source": "dem"},
    "sources": {"dem": {"type": "raster-dem", "tiles": ["dem/{z}/{x}/{y}.png"]}},
    "layers": []
}"#;

/// Ground of the same height everywhere, `None` where the heights are still
/// loading.
#[derive(Debug)]
struct Flat {
    height: Option<f64>,
    min: f64,
}

impl Elevation for Flat {
    fn at(&self, _: LatLng) -> Option<f64> {
        self.height
    }

    fn min_at(&self, _: LatLng) -> Option<f64> {
        Some(self.min)
    }

    fn surface_at(&self, _: DVec2) -> Option<f64> {
        Some(self.height.unwrap_or(0.0))
    }

    fn range(&self) -> Option<(f64, f64)> {
        let height = self.height.unwrap_or(0.0);
        Some((height, height))
    }
}

/// Sea level, with a plateau `height` meters high south of the world's `y`
/// (Web Mercator at zoom 0), which only the surface shows.
#[derive(Debug)]
pub(super) struct Plateau {
    pub(super) y: f64,
    pub(super) height: f64,
}

impl Elevation for Plateau {
    fn at(&self, _: LatLng) -> Option<f64> {
        Some(0.0)
    }

    fn min_at(&self, _: LatLng) -> Option<f64> {
        Some(0.0)
    }

    fn surface_at(&self, world: DVec2) -> Option<f64> {
        Some(if world.y > self.y { self.height } else { 0.0 })
    }

    fn range(&self) -> Option<(f64, f64)> {
        Some((self.height.min(0.0), self.height.max(0.0)))
    }
}

/// Ground that rises `rise` meters for each unit of Web Mercator x at zoom
/// 0 east of `x`, where it is `height` meters high, with a floor of
/// `height` under every center.
#[derive(Debug)]
pub(super) struct Slope {
    pub(super) x: f64,
    pub(super) height: f64,
    pub(super) rise: f64,
}

impl Slope {
    fn height(&self, world: DVec2) -> f64 {
        self.height + self.rise * (world.x.rem_euclid(1.0) - self.x)
    }
}

impl Elevation for Slope {
    fn at(&self, location: LatLng) -> Option<f64> {
        Some(self.height(world(&location.wrapped())))
    }

    fn min_at(&self, _: LatLng) -> Option<f64> {
        Some(self.height)
    }

    fn surface_at(&self, world: DVec2) -> Option<f64> {
        Some(self.height(world))
    }

    fn range(&self) -> Option<(f64, f64)> {
        let (west, east) = (self.height - self.rise * self.x, self.height + self.rise * (1.0 - self.x));
        Some((west.min(east), west.max(east)))
    }
}

pub(super) fn flat(height: Option<f64>, min: f64) -> Arc<dyn Elevation> {
    Arc::new(Flat { height, min })
}

/// The `n`th of a run of grounds that never settles: each is new, 100 m
/// high for an even `n` and 200 m for an odd one.
fn restless(n: usize) -> Arc<dyn Elevation> {
    flat(Some(if n.is_multiple_of(2) { 100.0 } else { 200.0 }), 100.0)
}

pub(super) fn ground_event(elevation: &Arc<dyn Elevation>) -> RendererEvent {
    RendererEvent::TerrainElevation(Some(Arc::clone(elevation)))
}

fn map(mode: MapMode, run_loop: &Queue<()>) -> Map {
    let file_source = StubFileSource::on_queue(run_loop, ResponseType::Asynchronous);
    let options = MapOptions { map_mode: mode, ..Default::default() };
    let mut map = super::test_map(file_source, options);
    map.load_style_json(STYLE);
    map.process_events();
    map
}

/// A 512 by 512 map of `style` that may pitch up to 180 degrees.
pub(super) fn pitchable(style: &str, run_loop: &Queue<()>) -> Map {
    let file_source = StubFileSource::on_queue(run_loop, ResponseType::Asynchronous);
    let options = MapOptions { size: mln_style::size::Size::new(512, 512), ..Default::default() };
    let mut map = super::test_map(file_source, options);
    map.load_style_json(style);
    map.process_events();
    map.set_bounds(&BoundOptions { max_pitch: Some(180.0), ..Default::default() }).unwrap();
    map
}

/// Where `location` is in Web Mercator at zoom 0.
pub(super) fn world(location: &LatLng) -> DVec2 {
    let point = crate::geo::projection::Projection::project(location, 1.0 / mln_style::constants::TILE_SIZE_D);
    DVec2::new(point.x, point.y)
}

/// Hands `event` to the map as its renderer would, and has the map handle it.
pub(super) fn report(map: &mut Map, event: RendererEvent) {
    map.renderer_events().push(event);
    map.process_events();
}

/// The center's altitude and the floor of the view's planes.
pub(super) fn ground(map: &Map) -> (f64, Option<f64>) {
    let view = map.transform_state().view();
    (view.center_altitude(), view.terrain_min_elevation())
}

/// Whether the map's latest update carries `elevation` as its ground.
fn carries(map: &Map, elevation: Option<&Arc<dyn Elevation>>) -> bool {
    let update = map.update_reader().latest().expect("an update");
    match (update.parameters.elevation.as_ref(), elevation) {
        (Some(carried), Some(elevation)) => std::ptr::addr_eq(Arc::as_ptr(carried), Arc::as_ptr(elevation)),
        (carried, elevation) => carried.is_none() && elevation.is_none(),
    }
}

/// The `update_id` of the map's latest update.
fn latest_update(map: &Map) -> u64 {
    map.update_reader().latest().map_or(0, |update| update.parameters.update_id)
}

/// The report of a frame in `mode` of the update `update_id`, of the still
/// image `still_image_request_id`, or of none with 0.
fn frame(mode: RenderMode, still_image_request_id: u64, update_id: u64) -> RendererEvent {
    RendererEvent::RenderFrameFinished {
        mode,
        needs_repaint: false,
        repaint_at: None,
        placement_changed: false,
        still_image_request_id,
        update_id,
        stats: Arc::default(),
        error: None,
    }
}

/// Reports a frame of the map's latest update in `mode`, of the still image
/// `still_image_request_id`, or of none with 0.
fn report_frame(map: &mut Map, mode: RenderMode, still_image_request_id: u64) {
    let update_id = latest_update(map);
    report(map, frame(mode, still_image_request_id, update_id));
}

fn camera_events(events: &[MapEvent]) -> usize {
    events.iter().filter(|event| matches!(event, MapEvent::CameraWillChange(_) | MapEvent::CameraDidChange(_))).count()
}

/// A camera at rest stands on the ground under its center, which the
/// update that answers the ground shows, without camera events. One that an
/// animation moves keeps its altitude, though the planes fit the terrain,
/// until it comes to rest.
#[test]
fn a_camera_at_rest_stands_on_the_ground_and_a_moving_one_holds() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Continuous, &run_loop);
    map.drain_events();

    let updates = map.update_generation();
    let ground = flat(Some(500.0), 300.0);
    report(&mut map, ground_event(&ground));
    assert_eq!((500.0, Some(300.0)), self::ground(&map));
    assert_eq!(updates + 1, map.update_generation(), "the answer's update");
    assert!(carries(&map, Some(&ground)));
    assert_eq!(0, camera_events(&map.drain_events()));

    map.update_camera(&CameraUpdate {
        mode: CameraUpdateMode::Ease,
        camera: CameraOptions { zoom: Some(10.0), ..Default::default() },
        animation: AnimationOptions { duration: Some(Duration::from_secs(60)), ..Default::default() },
        ..Default::default()
    });
    report(&mut map, ground_event(&flat(Some(800.0), 700.0)));
    let (altitude, floor) = self::ground(&map);
    assert_abs_diff_eq!(altitude, 500.0, epsilon = 1e-6);
    assert_eq!(Some(700.0), floor);

    map.cancel_transitions();
    let (altitude, _) = self::ground(&map);
    assert_abs_diff_eq!(altitude, 800.0, epsilon = 1e-6);
}

/// The terrain moves a camera at rest without camera events, whatever moves
/// it: ground that loads, changes or stops drawing under it, the clamp
/// turned on, and the style dropping its terrain. Hosts see those moves in
/// the snapshot.
#[test]
fn ground_at_rest_emits_no_camera_events() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Continuous, &run_loop);
    map.drain_events();
    let silent = |map: &mut Map, altitude: f64, what: &str| {
        assert_eq!(altitude, ground(map).0, "{what}");
        assert_eq!(0, camera_events(&map.drain_events()), "{what}");
    };

    report(&mut map, ground_event(&flat(Some(500.0), 300.0)));
    silent(&mut map, 500.0, "ground that loads");
    report(&mut map, ground_event(&flat(Some(800.0), 700.0)));
    silent(&mut map, 800.0, "ground that changes");
    report(&mut map, ground_event(&flat(Some(0.0), 0.0)));
    silent(&mut map, 0.0, "ground drawn flat");
    assert_eq!(Some(0.0), ground(&map).1, "ground drawn flat floors the view at sea level");
    report(&mut map, ground_event(&flat(Some(800.0), 700.0)));
    silent(&mut map, 800.0, "ground that rises again");
    report(&mut map, ground_event(&flat(None, 0.0)));
    silent(&mut map, 800.0, "ground that loads again");
    map.set_center_clamped_to_ground(false);
    report(&mut map, ground_event(&flat(Some(200.0), 100.0)));
    silent(&mut map, 800.0, "unclamped ground");
    map.set_center_clamped_to_ground(true);
    silent(&mut map, 200.0, "the clamp turned on");
    report(&mut map, RendererEvent::TerrainElevation(None));
    silent(&mut map, 0.0, "ground that stops drawing");
    report(&mut map, ground_event(&flat(Some(500.0), 300.0)));
    silent(&mut map, 500.0, "ground that draws again");
    map.edit_style(|style| style.apply(Edit::SetTerrain(None))).unwrap();
    silent(&mut map, 0.0, "the style's terrain dropped");
}

/// The map answers each new ground the renderer tells of with an update
/// that carries it, though the camera doesn't move: the renderer completes
/// a frame only of an update that carries its ground. Ground the map
/// already holds, which the renderer tells of again for an update that was
/// in flight, gets no update.
#[test]
fn each_ground_gets_an_update_that_carries_it() {
    let run_loop = Queue::<()>::new();
    for mode in [MapMode::Continuous, MapMode::Static] {
        let mut map = map(mode, &run_loop);
        if mode == MapMode::Static {
            map.render_still().unwrap();
        }
        let first = flat(Some(500.0), 300.0);
        report(&mut map, ground_event(&first));
        assert!(carries(&map, Some(&first)), "{mode:?}");

        let updates = map.update_generation();
        let same = flat(Some(500.0), 300.0);
        report(&mut map, ground_event(&same));
        assert_eq!((500.0, Some(300.0)), ground(&map), "{mode:?}: nothing moved");
        assert_eq!(updates + 1, map.update_generation(), "{mode:?}");
        assert!(carries(&map, Some(&same)), "{mode:?}");
        report(&mut map, ground_event(&same));
        assert_eq!(updates + 1, map.update_generation(), "{mode:?}: the ground it holds");

        report(&mut map, RendererEvent::TerrainElevation(None));
        assert!(carries(&map, None), "{mode:?}");
        report(&mut map, RendererEvent::TerrainElevation(None));
        assert_eq!(updates + 2, map.update_generation(), "{mode:?}: no ground again");
    }
}

/// With its center unclamped, the camera keeps the altitude it was given,
/// and the planes still fit the terrain.
#[test]
fn an_unclamped_center_keeps_its_altitude() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Continuous, &run_loop);
    map.set_center_clamped_to_ground(false);
    map.jump_to(&CameraOptions { center_altitude: Some(2000.0), ..Default::default() });
    report(&mut map, ground_event(&flat(Some(500.0), 300.0)));
    let (altitude, floor) = ground(&map);
    assert_abs_diff_eq!(altitude, 2000.0, epsilon = 1e-6);
    assert_eq!(Some(300.0), floor);

    // Clamping it again stands it on the ground.
    map.set_center_clamped_to_ground(true);
    assert_eq!((500.0, Some(300.0)), ground(&map));
}

/// Once terrain stops drawing, the planes fit the flat map and a clamped
/// center goes back to sea level, once: an altitude the camera takes while
/// the clamp is off stays once it is on again.
#[test]
fn the_camera_returns_to_sea_level_once_terrain_stops() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Continuous, &run_loop);
    report(&mut map, ground_event(&flat(Some(500.0), 300.0)));
    let flat_view = {
        let mut state = map.transform_state().clone();
        state.set_terrain_min_elevation(None);
        state.set_center_altitude(0.0);
        state.view().clone()
    };

    report(&mut map, RendererEvent::TerrainElevation(None));
    assert_eq!((0.0, None), ground(&map));
    assert_eq!(flat_view, *map.transform_state().view());

    map.set_center_clamped_to_ground(false);
    map.jump_to(&CameraOptions { center_altitude: Some(100.0), ..Default::default() });
    map.set_center_clamped_to_ground(true);
    map.trigger_repaint();
    let (altitude, _) = ground(&map);
    assert_abs_diff_eq!(altitude, 100.0, epsilon = 1e-6);
}

/// A still map that waits for no still image publishes no update, but its
/// camera stands on the ground all the same, and the next still image's
/// first update carries it.
#[test]
fn a_still_map_between_images_stands_on_the_ground() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Static, &run_loop);
    let ground_ = flat(Some(500.0), 300.0);
    report(&mut map, ground_event(&ground_));
    assert_eq!((500.0, Some(300.0)), ground(&map));
    map.render_still().unwrap();
    assert!(carries(&map, Some(&ground_)));
    report(&mut map, RendererEvent::TerrainElevation(None));
    assert_eq!((0.0, None), ground(&map));
}

/// Only a complete frame ends a still image or leaves a continuous map
/// idle: the renderer reports one of an update that carries an earlier
/// ground as partial.
#[test]
fn a_partial_frame_ends_no_still_and_no_idle() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Static, &run_loop);
    map.render_still().unwrap();
    report_frame(&mut map, RenderMode::Partial, 1);
    assert_eq!(None, map.take_still_image());
    report_frame(&mut map, RenderMode::Full, 1);
    assert_eq!(Some(Ok(())), map.take_still_image());

    let mut map = self::map(MapMode::Continuous, &run_loop);
    map.drain_events();
    let idle = |events: Vec<MapEvent>| events.iter().any(|event| matches!(event, MapEvent::Idle));
    report_frame(&mut map, RenderMode::Partial, 0);
    assert!(!idle(map.drain_events()));
    report_frame(&mut map, RenderMode::Full, 0);
    assert!(idle(map.drain_events()));
}

/// A continuous map goes idle only on a frame of its last update. A frame
/// that took in new ground, or a tile's data whose wake reaches the map
/// late, reports it before it finishes, and the map answers with an
/// update: the frame, complete as it is, leaves that update to draw, and
/// the update's frame leaves the map idle, once.
#[test]
fn a_continuous_map_goes_idle_only_on_a_frame_of_its_last_update() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Continuous, &run_loop);
    let idle = |map: &mut Map| map.drain_events().iter().filter(|event| matches!(event, MapEvent::Idle)).count();
    for (what, taken_in) in
        [("new ground", ground_event(&flat(Some(0.0), 0.0))), ("a late wake", RendererEvent::Invalidate)]
    {
        report_frame(&mut map, RenderMode::Full, 0);
        assert_eq!(1, idle(&mut map), "the map isn't idle before {what}");
        let drawn = latest_update(&map);
        map.renderer_events().push(taken_in);
        map.renderer_events().push(frame(RenderMode::Full, 0, drawn));
        map.process_events();
        assert_ne!(drawn, latest_update(&map), "the map answers {what} with an update");
        assert_eq!(0, idle(&mut map), "idle on a frame before the answer to {what}");
        let answer = latest_update(&map);
        report_frame(&mut map, RenderMode::Full, 0);
        assert_eq!(1, idle(&mut map), "the answer to {what} leaves the map idle");
        assert_eq!(answer, latest_update(&map), "the idle map asks for another frame after {what}");
    }
}

/// A camera whose ground changes with each move stops following it after
/// eight moves in a still image, though the map still answers each ground
/// with an update that carries it, so the renderer completes the image.
#[test]
fn a_still_image_stops_following_ground_that_never_settles() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Static, &run_loop);
    map.render_still().unwrap();
    let mut altitudes = Vec::new();
    for n in 0..20 {
        let updates = map.update_generation();
        let ground_ = restless(n);
        report(&mut map, ground_event(&ground_));
        assert_eq!(updates + 1, map.update_generation(), "an answer to each");
        assert!(carries(&map, Some(&ground_)));
        altitudes.push(ground(&map).0);
    }
    let mut moves = [100.0, 200.0].repeat(4);
    moves.extend([200.0; 12]);
    assert_eq!(moves, altitudes);
    report_frame(&mut map, RenderMode::Full, 1);
    assert_eq!(Some(Ok(())), map.take_still_image());

    // The next still image follows the ground again.
    map.render_still().unwrap();
    report(&mut map, ground_event(&restless(0)));
    assert_eq!(100.0, ground(&map).0);
}

/// A style that drops its terrain while a still image waits takes the
/// camera back to the flat map at once, before the renderer has drawn the
/// style without terrain, and its updates carry no ground.
#[test]
fn a_style_without_terrain_lets_go_of_the_ground() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Static, &run_loop);
    map.render_still().unwrap();
    let ground_ = flat(Some(500.0), 300.0);
    report(&mut map, ground_event(&ground_));
    assert_eq!((500.0, Some(300.0)), ground(&map));

    map.edit_style(|style| style.apply(Edit::SetTerrain(None))).unwrap();
    assert_eq!((0.0, None), ground(&map));
    assert!(carries(&map, None));
    // A ground the renderer sent before it drew the flat map doesn't ground
    // the camera again.
    report(&mut map, ground_event(&ground_));
    assert_eq!((0.0, None), ground(&map));
    assert!(carries(&map, None));
}

/// A still image that used up its moves on ground that never settles still
/// goes back to the flat map once terrain stops drawing.
#[test]
fn the_camera_returns_to_sea_level_after_a_still_image_used_its_moves() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Static, &run_loop);
    map.render_still().unwrap();
    for n in 0..10 {
        report(&mut map, ground_event(&restless(n)));
    }
    assert!(ground(&map).0 > 0.0);
    report(&mut map, RendererEvent::TerrainElevation(None));
    assert_eq!((0.0, None), ground(&map));
    assert!(carries(&map, None));
}

/// An animation of the pitch alone eases the altitude onto ground that
/// lands under the center, by its end, rather than jumping onto it. One of
/// the altitude alone, which the clamp decides, has nothing to animate: it
/// ends at once, with the center on the ground.
#[test]
fn a_pitch_animation_eases_onto_ground_that_lands() {
    let animate = |map: &mut Map, camera| {
        map.update_camera(&CameraUpdate {
            mode: CameraUpdateMode::Ease,
            camera,
            animation: AnimationOptions { duration: Some(Duration::from_secs(60)), ..Default::default() },
            ..Default::default()
        });
        map.trigger_repaint();
    };
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Continuous, &run_loop);
    report(&mut map, ground_event(&flat(Some(500.0), 300.0)));
    animate(&mut map, CameraOptions { center_altitude: Some(2000.0), ..Default::default() });
    assert!(!map.snapshot().transition_in_progress, "the altitude alone");
    assert_eq!(500.0, ground(&map).0, "the altitude alone");

    animate(&mut map, CameraOptions { pitch: Some(40.0), ..Default::default() });
    report(&mut map, ground_event(&flat(Some(800.0), 700.0)));
    let (altitude, min) = ground(&map);
    assert_eq!(Some(700.0), min);
    assert!((500.0..501.0).contains(&altitude), "a minute's pitch heads for the ground slowly: {altitude}");

    map.cancel_transitions();
    let (altitude, _) = ground(&map);
    assert_abs_diff_eq!(altitude, 800.0, epsilon = 1e-6);
}

/// A jump that would put the eye below sea level before the renderer drew
/// any ground raises it to sea level by pitch and zoom, with the eye where
/// it was across the ground and the center where the jump put it.
#[test]
fn a_jump_below_sea_level_before_any_ground_looks_from_sea_level() {
    let run_loop = Queue::<()>::new();
    let mut map = pitchable(STYLE, &run_loop);
    let center = LatLng::new(47.34487, 11.52517).unwrap();
    map.jump_to(&CameraOptions {
        center: Some(center),
        zoom: Some(13.0),
        pitch: Some(95.0),
        center_altitude: Some(0.0),
        ..Default::default()
    });
    let camera = map.transform_state().camera_options(None);
    assert_abs_diff_eq!(90.0, camera.pitch.unwrap(), epsilon = 1e-9);
    assert_abs_diff_eq!(13.0 + (1.0 / 95f64.to_radians().sin()).log2(), camera.zoom.unwrap(), epsilon = 1e-9);
    let moved = map.transform_state().view().center(WrapMode::Unwrapped);
    assert_abs_diff_eq!(center.latitude(), moved.latitude(), epsilon = 1e-9);
    assert_abs_diff_eq!(center.longitude(), moved.longitude(), epsilon = 1e-9);
    assert_eq!(0.0, camera.center_altitude.unwrap());
}

/// A jump that would put the eye, or the near plane, into raised ground is
/// raised by pitch and zoom until both clear it, keeping the center, its
/// altitude and the bearing. The eye would be about 2,300 m below the
/// plateau.
#[test]
fn a_jump_into_raised_ground_keeps_the_eye_above_it() {
    let run_loop = Queue::<()>::new();
    let mut map = pitchable(STYLE, &run_loop);
    map.set_center_clamped_to_ground(false);
    let center = LatLng::new(20.0, 10.0).unwrap();
    let plateau = Plateau { y: world(&center).y + 1e-6, height: 4000.0 };
    let surface = |point: glam::DVec3| plateau.surface_at(point.truncate()).unwrap();
    report(
        &mut map,
        ground_event(&{
            let plateau: Arc<dyn Elevation> = Arc::new(Plateau { ..plateau });
            plateau
        }),
    );
    let jump = CameraOptions {
        center: Some(center),
        zoom: Some(14.0),
        pitch: Some(70.0),
        bearing: Some(30.0),
        center_altitude: Some(500.0),
        ..Default::default()
    };
    map.jump_to(&jump);

    let view = map.transform_state().view();
    let eye = view.eye_position();
    assert!(eye.z >= surface(eye), "the eye at {eye}");
    // The raises only approach the ground: they leave the near plane less
    // than a thousandth of a pixel short, out of sight.
    let tolerance = view.meters_per_pixel() / 1000.0;
    for point in view.near_plane_points() {
        assert!(point.z >= surface(point) - tolerance, "the near plane at {point}");
    }
    let camera = map.transform_state().camera_options(None);
    assert!(camera.pitch.unwrap() < 70.0 && camera.zoom.unwrap() < 14.0, "{camera:?}");
    let moved = view.center(WrapMode::Unwrapped);
    assert_abs_diff_eq!(center.latitude(), moved.latitude(), epsilon = 1e-9);
    assert_abs_diff_eq!(center.longitude(), moved.longitude(), epsilon = 1e-9);
    assert_eq!(500.0, camera.center_altitude.unwrap());
    assert_abs_diff_eq!(30.0, camera.bearing.unwrap(), epsilon = 1e-9);
}

/// Without terrain, a jump keeps the pitch it was given, though the eye is
/// below sea level.
#[test]
fn without_terrain_a_pitch_95_jump_stays_at_95() {
    let run_loop = Queue::<()>::new();
    let mut map = pitchable(r#"{"version": 8, "sources": {}, "layers": []}"#, &run_loop);
    map.jump_to(&CameraOptions { zoom: Some(13.0), pitch: Some(95.0), ..Default::default() });
    assert!(map.transform_state().view().eye_position().z < 0.0);
    assert_abs_diff_eq!(95.0, map.transform_state().camera_options(None).pitch.unwrap(), epsilon = 1e-9);
    assert_eq!(Some(13.0), map.transform_state().camera_options(None).zoom);
}

/// Ground that loads above the eye of a camera at rest, or above its near
/// plane, as under a camera that a jump placed before any ground drew,
/// raises the eye by pitch and zoom without camera events, keeping the
/// eye's place across the ground, the bearing and the center on the ground
/// under it. The eye would be about 2,500 m below the plateau. Once clear,
/// the camera stays where it is.
#[test]
fn ground_that_loads_over_a_resting_eye_raises_it() {
    let run_loop = Queue::<()>::new();
    for mode in [MapMode::Continuous, MapMode::Static] {
        let mut map = pitchable(STYLE, &run_loop);
        if mode == MapMode::Static {
            map = self::map(mode, &run_loop);
            map.render_still().unwrap();
        }
        let center = LatLng::new(20.0, 10.0).unwrap();
        map.jump_to(&CameraOptions {
            center: Some(center),
            zoom: Some(14.0),
            pitch: Some(60.0),
            bearing: Some(30.0),
            ..Default::default()
        });
        map.drain_events();
        let eye = map.transform_state().view().eye_position();

        let plateau = Plateau { y: world(&center).y + 1e-6, height: 4000.0 };
        let surface = |point: glam::DVec3| plateau.surface_at(point.truncate()).unwrap();
        let ground_: Arc<dyn Elevation> = Arc::new(Plateau { ..plateau });
        report(&mut map, ground_event(&ground_));

        let view = map.transform_state().view().clone();
        let raised = view.eye_position();
        assert!(raised.z >= surface(raised), "{mode:?}: the eye at {raised}");
        let tolerance = view.meters_per_pixel() / 1000.0;
        for point in view.near_plane_points() {
            assert!(point.z >= surface(point) - tolerance, "{mode:?}: the near plane at {point}");
        }
        assert_abs_diff_eq!(eye.truncate(), raised.truncate(), epsilon = 1e-12);
        let camera = map.transform_state().camera_options(None);
        assert!(camera.pitch.unwrap() < 60.0 && camera.zoom.unwrap() < 14.0, "{mode:?}: {camera:?}");
        assert_abs_diff_eq!(30.0, camera.bearing.unwrap(), epsilon = 1e-9);
        let moved = view.center(WrapMode::Unwrapped);
        assert_abs_diff_eq!(center.latitude(), moved.latitude(), epsilon = 1e-9);
        assert_abs_diff_eq!(center.longitude(), moved.longitude(), epsilon = 1e-9);
        assert_eq!(0.0, camera.center_altitude.unwrap(), "{mode:?}");
        assert_eq!(0, camera_events(&map.drain_events()), "{mode:?}");

        map.trigger_repaint();
        assert_eq!(view, *map.transform_state().view(), "{mode:?}");
    }
}

/// A resting eye that ground raised lowers again, back to the zoom and
/// pitch that the camera was given, once the ground under its center rises
/// to clear it: the camera comes to stand where the ground it ends on puts
/// it, whatever order that ground loaded in. A still image then shows the
/// camera that was asked for.
#[test]
fn a_raised_resting_eye_lowers_again_once_the_ground_clears_it() {
    let run_loop = Queue::<()>::new();
    let center = LatLng::new(20.0, 10.0).unwrap();
    let camera = CameraOptions {
        center: Some(center),
        zoom: Some(14.0),
        pitch: Some(60.0),
        bearing: Some(30.0),
        ..Default::default()
    };
    for mode in [MapMode::Continuous, MapMode::Static] {
        let new_map = || {
            let mut map = if mode == MapMode::Static { map(mode, &run_loop) } else { pitchable(STYLE, &run_loop) };
            if mode == MapMode::Static {
                map.render_still().unwrap();
            }
            map.jump_to(&camera);
            map
        };
        let landed = flat(Some(4000.0), 4000.0);

        // The ground toward the eye loads first, while the center's is at sea
        // level, and raises the eye.
        let mut map = new_map();
        let plateau: Arc<dyn Elevation> = Arc::new(Plateau { y: world(&center).y + 1e-6, height: 4000.0 });
        report(&mut map, ground_event(&plateau));
        let raised = map.transform_state().camera_options(None);
        assert!(raised.pitch.unwrap() < 60.0 && raised.zoom.unwrap() < 14.0, "{mode:?}: {raised:?}");

        // The center's ground lands on the plateau too, with the eye clear
        // of it at the camera that was asked for.
        report(&mut map, ground_event(&landed));
        let lowered = map.transform_state().camera_options(None);
        assert_abs_diff_eq!(60.0, lowered.pitch.unwrap(), epsilon = 1e-9);
        assert_abs_diff_eq!(14.0, lowered.zoom.unwrap(), epsilon = 1e-9);
        assert_eq!(4000.0, lowered.center_altitude.unwrap(), "{mode:?}");

        // As where the ground loaded at once, but for rounding.
        let mut direct = new_map();
        report(&mut direct, ground_event(&landed));
        let eye = |map: &Map| map.transform_state().view().eye_position();
        assert_abs_diff_eq!(eye(&direct), eye(&map), epsilon = 1e-6);
    }
}

/// Sea level with a ledge `height` meters high under every center, and a
/// plateau `plateau` meters high south of the world's `y` (Web Mercator at
/// zoom 0), which only the surface shows.
#[derive(Debug)]
struct Ledge {
    y: f64,
    height: f64,
    plateau: f64,
}

impl Elevation for Ledge {
    fn at(&self, _: LatLng) -> Option<f64> {
        Some(self.height)
    }

    fn min_at(&self, _: LatLng) -> Option<f64> {
        Some(self.height)
    }

    fn surface_at(&self, world: DVec2) -> Option<f64> {
        Some(if world.y > self.y { self.plateau } else { self.height })
    }

    fn range(&self) -> Option<(f64, f64)> {
        Some((self.height, self.plateau))
    }
}

/// Ground that stops drawing while the style keeps its terrain takes a
/// clamped center back to sea level, and a resting eye that ground raised
/// is placed again from the camera that was asked for: the ground under the
/// center changed.
#[test]
fn a_raised_resting_eye_is_placed_again_once_the_ground_stops_drawing() {
    let run_loop = Queue::<()>::new();
    let mut map = pitchable(STYLE, &run_loop);
    let center = LatLng::new(20.0, 10.0).unwrap();
    map.jump_to(&CameraOptions { center: Some(center), zoom: Some(14.0), pitch: Some(60.0), ..Default::default() });
    let ledge: Arc<dyn Elevation> = Arc::new(Ledge { y: world(&center).y + 1e-6, height: 500.0, plateau: 4500.0 });
    report(&mut map, ground_event(&ledge));
    let raised = map.transform_state().camera_options(None);
    assert!(raised.zoom.unwrap() < 14.0, "{raised:?}");
    assert_eq!(500.0, raised.center_altitude.unwrap());

    report(&mut map, RendererEvent::TerrainElevation(None));
    let placed = map.transform_state().camera_options(None);
    assert_eq!(0.0, placed.center_altitude.unwrap());
    assert_abs_diff_eq!(14.0, placed.zoom.unwrap(), epsilon = 1e-9);
    assert_abs_diff_eq!(60.0, placed.pitch.unwrap(), epsilon = 1e-9);
}

/// Sea level whose surface hasn't drawn yet: the heights under the center
/// are known, and the ground around it shows nothing.
#[derive(Debug)]
struct Undrawn;

impl Elevation for Undrawn {
    fn at(&self, _: LatLng) -> Option<f64> {
        Some(0.0)
    }

    fn min_at(&self, _: LatLng) -> Option<f64> {
        Some(0.0)
    }

    fn surface_at(&self, _: DVec2) -> Option<f64> {
        None
    }

    fn range(&self) -> Option<(f64, f64)> {
        Some((0.0, 0.0))
    }
}

/// A 512 by 512 map at zoom 14 and pitch 60 over the center, whose eye a
/// plateau toward it raised, and the zoom and pitch the plateau left.
fn raised_by_a_plateau(run_loop: &Queue<()>) -> (Map, (f64, f64)) {
    let mut map = pitchable(STYLE, run_loop);
    let center = LatLng::new(20.0, 10.0).unwrap();
    map.jump_to(&CameraOptions { center: Some(center), zoom: Some(14.0), pitch: Some(60.0), ..Default::default() });
    let plateau: Arc<dyn Elevation> = Arc::new(Plateau { y: world(&center).y + 1e-6, height: 4000.0 });
    report(&mut map, ground_event(&plateau));
    let raised = map.transform_state().camera_options(None);
    assert!(raised.zoom.unwrap() < 14.0 && raised.pitch.unwrap() < 60.0, "{raised:?}");
    (map, (raised.zoom.unwrap(), raised.pitch.unwrap()))
}

/// The zoom and pitch of `map`'s camera.
fn zoom_and_pitch(map: &Map) -> (f64, f64) {
    let camera = map.transform_state().camera_options(None);
    (camera.zoom.unwrap(), camera.pitch.unwrap())
}

/// Ground still loading under the eye of the camera that was asked for
/// shows nothing about whether that camera clears it, and leaves a resting
/// eye that ground raised where it is, as the ground under the camera's own
/// moves would otherwise swing it up and down. Once the ground there is
/// known to clear it, the camera that was asked for comes back.
#[test]
fn a_raised_resting_eye_lowers_only_on_ground_known_to_clear_it() {
    let run_loop = Queue::<()>::new();
    let (mut map, raised) = raised_by_a_plateau(&run_loop);

    let undrawn: Arc<dyn Elevation> = Arc::new(Undrawn);
    report(&mut map, ground_event(&undrawn));
    assert_eq!(raised, zoom_and_pitch(&map));

    report(&mut map, ground_event(&flat(Some(0.0), 0.0)));
    let (zoom, pitch) = zoom_and_pitch(&map);
    assert_abs_diff_eq!(14.0, zoom, epsilon = 1e-9);
    assert_abs_diff_eq!(60.0, pitch, epsilon = 1e-9);
}

/// Turning the clamp off leaves a resting eye that ground still reaches
/// raised as far as the ground needs.
#[test]
fn unclamping_a_raised_resting_eye_keeps_the_raise_its_ground_needs() {
    let run_loop = Queue::<()>::new();
    let (mut map, raised) = raised_by_a_plateau(&run_loop);
    map.set_center_clamped_to_ground(false);
    map.trigger_repaint();
    let (zoom, pitch) = zoom_and_pitch(&map);
    assert_abs_diff_eq!(raised.0, zoom, epsilon = 1e-9);
    assert_abs_diff_eq!(raised.1, pitch, epsilon = 1e-9);
}

/// A style that drops its terrain gives a resting eye that only the terrain
/// raised the zoom and pitch it was asked for again.
#[test]
fn a_raised_resting_eye_lowers_once_the_terrain_goes() {
    let run_loop = Queue::<()>::new();
    let (mut map, _) = raised_by_a_plateau(&run_loop);
    map.edit_style(|style| style.apply(Edit::SetTerrain(None))).unwrap();
    let (zoom, pitch) = zoom_and_pitch(&map);
    assert_abs_diff_eq!(14.0, zoom, epsilon = 1e-9);
    assert_abs_diff_eq!(60.0, pitch, epsilon = 1e-9);
}

/// Ground whose drawn surface is `drawn`, as a raised camera's coarser
/// tiles draw it, and whose finest loaded DEM data is `finest`.
#[derive(Debug)]
struct Coarse {
    drawn: Arc<dyn Elevation>,
    finest: Arc<dyn Elevation>,
}

impl Elevation for Coarse {
    fn at(&self, location: LatLng) -> Option<f64> {
        self.drawn.at(location)
    }

    fn min_at(&self, location: LatLng) -> Option<f64> {
        self.drawn.min_at(location)
    }

    fn surface_at(&self, world: DVec2) -> Option<f64> {
        self.drawn.surface_at(world)
    }

    fn ground_at(&self, location: LatLng) -> Option<f64> {
        self.finest.at(location)
    }

    fn clearance_at(&self, world: DVec2) -> Option<f64> {
        self.finest.surface_at(world)
    }

    fn range(&self) -> Option<(f64, f64)> {
        self.drawn.range()
    }
}

/// Fine DEM data with a ridge toward the eye raises it, and the raised view
/// draws coarser tiles, which smooth the ridge away: the eye clears the
/// finest data loaded, which still has the ridge, and stays raised, or the
/// camera would lower onto the ridge and rise again. Once the finest data
/// clears the camera that was asked for, that camera comes back.
#[test]
fn a_raised_resting_eye_clears_the_finest_ground_whatever_draws() {
    let run_loop = Queue::<()>::new();
    let (mut map, raised) = raised_by_a_plateau(&run_loop);
    let center = LatLng::new(20.0, 10.0).unwrap();
    let ridge: Arc<dyn Elevation> = Arc::new(Plateau { y: world(&center).y + 1e-6, height: 4000.0 });

    let coarse: Arc<dyn Elevation> = Arc::new(Coarse { drawn: flat(Some(0.0), 0.0), finest: ridge });
    report(&mut map, ground_event(&coarse));
    assert_eq!(raised, zoom_and_pitch(&map));

    report(&mut map, ground_event(&flat(Some(0.0), 0.0)));
    let (zoom, pitch) = zoom_and_pitch(&map);
    assert_abs_diff_eq!(14.0, zoom, epsilon = 1e-9);
    assert_abs_diff_eq!(60.0, pitch, epsilon = 1e-9);
}

/// A resting center stands on the finest DEM data loaded, though the frame
/// draws the tile under it flat, as a zoomed-out view draws a tile whose
/// own DEM is still loading: where it stands doesn't depend on which camera
/// drew the frame.
#[test]
fn a_resting_center_stands_on_the_finest_ground_whatever_draws() {
    let run_loop = Queue::<()>::new();
    let mut map = map(MapMode::Continuous, &run_loop);
    let coarse: Arc<dyn Elevation> = Arc::new(Coarse { drawn: flat(Some(0.0), 0.0), finest: flat(Some(500.0), 500.0) });
    report(&mut map, ground_event(&coarse));
    assert_eq!(500.0, ground(&map).0);
}