mln-rs-engine 0.0.22

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
//! The world square's mappings: Mercator's, and a registered projection's
//! through its converter, where the converter has no answer too.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use approx::{assert_abs_diff_eq, assert_relative_eq};
use mln_style::constants::{LATITUDE_MAX, TILE_SIZE_D};
use mln_style::crs::{Crs, CrsConverter, WorldMapping};
use mln_style::geo::{LatLng, LatLngBounds};
use mln_style::geometry::Point;

use crate::geo::constants::EARTH_RADIUS_M;
use crate::geo::projection::Projection;
use crate::tests::crs::{self, crs, identity, mapping};

fn ll(lat: f64, lng: f64) -> LatLng {
    LatLng::new(lat, lng).unwrap()
}

fn lat_lng(world: &WorldMapping, x: f64, y: f64) -> LatLng {
    world.lat_lng_from_world(&Point::new(x, y)).unwrap()
}

/// Locations near the poles, at the origin and in cities on several
/// continents, `[lng, lat]`.
const SAMPLES: [[f64; 2]; 6] =
    [[0.0, 0.0], [-89.0, -89.0], [89.0, 89.0], [12.5, 41.9], [-73.98, 40.75], [174.77, -41.29]];

/// The identity, with an inverse that answers only inside its tile matrix
/// set, -90 to 90 on both axes.
fn identity_answering_inside() -> WorldMapping {
    mapping(crs(
        "test:identity-answering-inside",
        |position| position,
        |[x, y]| if x.abs() <= 90.0 && y.abs() <= 90.0 { [x, y] } else { [f64::NAN; 2] },
        [-90.0, 90.0],
        180.0,
    ))
}

/// A lng/lat rotated by 30 degrees.
fn rotate([lng, lat]: [f64; 2]) -> [f64; 2] {
    let (sin, cos) = (std::f64::consts::PI / 6.0).sin_cos();
    [lng * cos - lat * sin, lng * sin + lat * cos]
}

/// A CRS rotated by 30 degrees, its tile matrix set 300 units wide.
fn rotated() -> WorldMapping {
    let (sin, cos) = (std::f64::consts::PI / 6.0).sin_cos();
    mapping(crs("test:rotated", rotate, move |[x, y]| [x * cos + y * sin, -x * sin + y * cos], [-150.0, 150.0], 300.0))
}

/// Spherical Mercator written as a CRS, so its world coordinates can be
/// checked against Mercator's own.
fn mercator_as_crs() -> WorldMapping {
    let half_circumference = std::f64::consts::PI * EARTH_RADIUS_M;
    mapping(crs(
        "test:mercator-as-crs",
        |[lng, lat]| {
            let phi = lat.to_radians();
            [lng.to_radians() * EARTH_RADIUS_M, EARTH_RADIUS_M * (std::f64::consts::FRAC_PI_4 + phi / 2.0).tan().ln()]
        },
        |[x, y]| {
            [
                (x / EARTH_RADIUS_M).to_degrees(),
                (2.0 * (y / EARTH_RADIUS_M).exp().atan() - std::f64::consts::FRAC_PI_2).to_degrees(),
            ]
        },
        [-half_circumference, half_circumference],
        2.0 * half_circumference,
    ))
}

/// The identity takes lng/lat as its coordinates: tile 0's square spans 90
/// degrees each way from the origin, locations round trip, and a world unit
/// is its zoom 0 extent in meters wherever it is.
#[test]
fn the_identity_takes_lng_lat_as_its_coordinates() {
    let world = identity();
    assert_eq!("identity", world.name());
    assert!(!world.wraps());
    for ((lat, lng), place) in [
        ((45.0, 45.0), (0.75, 0.25)),
        ((90.0, -90.0), (0.0, 0.0)),
        ((-90.0, 90.0), (1.0, 1.0)),
        ((0.0, 0.0), (0.5, 0.5)),
    ] {
        assert_eq!(Point::new(place.0, place.1), world.world_from_lat_lng(&ll(lat, lng)));
    }
    assert_eq!(ll(45.0, 45.0), lat_lng(&world, 0.75, 0.25));
    for [lng, lat] in SAMPLES {
        let back = world.lat_lng_from_world(&world.world_from_lat_lng(&ll(lat, lng))).unwrap();
        assert_abs_diff_eq!(lng, back.longitude(), epsilon = 5e-13);
        assert_abs_diff_eq!(lat, back.latitude(), epsilon = 5e-13);
    }
    for (x, y) in [(0.5, 0.5), (0.95, 0.05)] {
        assert_eq!(180.0, world.height_meters_per_world_unit(&lat_lng(&world, x, y)));
    }
    assert_eq!([-90.0, 90.0], world.latitude_range());
}

// On Mercator, a world unit spans the length of the parallel at the latitude
// on the ground, within its limit, along any step: what `Projection` makes a
// pixel at zoom 0, times the world's 512 pixels.
#[test]
fn mercator_measures_the_ground_in_closed_form() {
    let mercator = WorldMapping::default();
    for latitude in [0.0, 45.0, -60.0, LATITUDE_MAX, 89.0] {
        let expected = Projection::meters_per_pixel_at_latitude(latitude, 0.0) * TILE_SIZE_D;
        for step in [[1e-3, 0.0], [0.0, 1e-3], [0.5, 0.5]] {
            let measured = mercator.ground_meters_per_world_unit([10.0, latitude], step);
            assert_relative_eq!(expected, measured, max_relative = 1e-15);
        }
    }
}

// In a registered projection, a world unit spans the ground distance across
// a step over the step's length, which can change with the direction: the
// identity's world unit is 180 degrees of latitude along y, and of longitude
// along x, whose length shrinks with the latitude.
#[test]
fn the_identity_measures_the_ground_across_a_step() {
    let world = identity();
    let half_meridian = std::f64::consts::PI * 6_371_008.8;
    let step = 1e-4;
    let along_x = |latitude| world.ground_meters_per_world_unit([0.0, latitude], [step, 0.0]);
    assert_relative_eq!(half_meridian, along_x(0.0), max_relative = 1e-6);
    assert_relative_eq!(half_meridian / 2.0, along_x(60.0), max_relative = 1e-6);
    assert_relative_eq!(
        half_meridian,
        world.ground_meters_per_world_unit([0.0, 60.0], [0.0, step]),
        max_relative = 1e-6
    );
}

#[test]
fn a_lat_lng_past_the_edge_of_the_square_is_unclamped() {
    let world = identity();
    // The identity has an answer everywhere: a position east of the square
    // keeps its own longitude.
    assert_eq!(ll(0.0, 135.0), lat_lng(&world, 1.25, 0.5));
    assert!(world.has_lat_lng(&Point::new(1.25, 0.5)));
    assert_eq!(ll(90.0, 0.0), lat_lng(&world, 0.5, -0.5));
}

#[test]
fn a_latitude_past_the_poles_is_clamped() {
    let world = identity();
    assert_eq!(90.0, lat_lng(&world, 0.5, -0.1).latitude());
    assert_eq!(-90.0, lat_lng(&world, 0.5, 1.1).latitude());
    assert!(!world.has_lat_lng(&Point::new(0.5, -0.1)));
}

#[test]
fn a_position_without_an_answer_uses_the_edge_toward_the_center() {
    let world = mapping(crs::disc("test:disc"));
    assert!(!world.has_lat_lng(&Point::new(1.0, 1.0)));
    assert!(world.has_lat_lng(&Point::new(0.5, 0.5)));
    // The corner of the square has no answer, nor any position past it; the
    // last one with an answer on the line to the center is on the disc.
    let edge = lat_lng(&world, 2.0, 2.0);
    assert_abs_diff_eq!(90.0, edge.longitude().hypot(edge.latitude()), epsilon = 1e-6);
    assert_abs_diff_eq!(-edge.latitude(), edge.longitude(), epsilon = 1e-9);
    // A position past the square whose clamped one has an answer uses that
    // one.
    assert_eq!(ll(0.0, 90.0), lat_lng(&world, 1.5, 0.5));
}

/// A converter that counts its calls of `forward`.
struct CountingForward {
    converter: Box<dyn CrsConverter>,
    forward_calls: Arc<AtomicUsize>,
}

impl CrsConverter for CountingForward {
    fn forward(&self, lng_lats: &[[f64; 2]], positions: &mut [[f64; 2]]) {
        self.forward_calls.fetch_add(1, Ordering::SeqCst);
        self.converter.forward(lng_lats, positions);
    }

    fn inverse(&self, positions: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
        self.converter.inverse(positions, lng_lats);
    }
}

#[test]
fn a_hole_in_a_batch_stays_while_its_neighbors_convert() {
    let Crs { converter, tile_matrix_set, .. } = crs::disc("test:batch");
    let forward_calls = Arc::new(AtomicUsize::new(0));
    let converter = Box::new(CountingForward { converter, forward_calls: Arc::clone(&forward_calls) });
    let world = mapping(Crs { name: "test:batch".to_owned(), converter, tile_matrix_set });

    let mut places = [[0.0; 2]; 3];
    world.world_from_lng_lats(&[[-45.0, 45.0], [f64::NAN, f64::NAN], [45.0, -45.0]], &mut places);
    assert_eq!(1, forward_calls.load(Ordering::SeqCst));
    assert_eq!([0.25, 0.25], places[0]);
    assert!(places[1][0].is_nan() && places[1][1].is_nan());
    assert_eq!([0.75, 0.75], places[2]);

    // The corner between them has no answer of its own and falls back to the
    // edge of the disc, while they keep theirs.
    let mut answers = [[0.0; 2]; 3];
    world.lng_lats_from_world(&[[0.25, 0.25], [1.0, 1.0], [0.75, 0.75]], &mut answers);
    assert_eq!([-45.0, 45.0], answers[0]);
    assert_abs_diff_eq!(90.0, answers[1][0].hypot(answers[1][1]), epsilon = 1e-6);
    assert_abs_diff_eq!(-answers[1][1], answers[1][0], epsilon = 1e-9);
    assert_eq!([45.0, -45.0], answers[2]);
}

#[test]
fn a_position_past_the_east_edge_takes_the_nearest_answer_inside() {
    assert_eq!(ll(45.0, 90.0), lat_lng(&identity_answering_inside(), 1.5, 0.25));
}

#[test]
fn a_position_past_the_edge_of_the_world_takes_the_edge_where_the_inverse_wraps() {
    let world = mapping(crs(
        "test:wrapping-world",
        |position| position,
        |[x, y]| [(x + 540.0) % 360.0 - 180.0, y],
        [-360.0, 360.0],
        720.0,
    ));
    let past_the_east_edge = lat_lng(&world, 0.875, 0.5);
    assert_abs_diff_eq!(180.0, past_the_east_edge.longitude(), epsilon = 5e-6);
    assert_abs_diff_eq!(0.0, past_the_east_edge.latitude(), epsilon = 5e-6);
}

#[test]
fn a_nearly_invertible_converter_keeps_its_inverse() {
    let world = mapping(crs("test:approximate", |position| position, |[x, y]| [x * 1.0001, y], [-90.0, 90.0], 180.0));
    assert_abs_diff_eq!(45.0045, lat_lng(&world, 0.75, 0.5).longitude(), epsilon = 5e-7);
}

#[test]
fn a_converter_that_never_leads_back_keeps_its_own_answer() {
    let world = mapping(crs("test:imprecise", |position| position, |[x, y]| [x + 1.0, y], [-90.0, 90.0], 180.0));
    assert_eq!(ll(0.0, 1.0), lat_lng(&world, 0.5, 0.5));
}

#[test]
fn a_position_has_no_location_where_the_inverse_never_answers() {
    let world = mapping(crs("test:never", |position| position, |_| [f64::NAN; 2], [-90.0, 90.0], 180.0));
    assert!(world.lat_lng_from_world(&Point::new(0.5, 0.5)).is_err());
    let mut lng_lats = [[0.0; 2]];
    world.lng_lats_from_world(&[[0.5, 0.5]], &mut lng_lats);
    assert!(lng_lats[0][0].is_nan() && lng_lats[0][1].is_nan());
}

// A rotated CRS round trips lng/lat, measures world coordinates from the
// tile matrix set's origin with y growing down, and takes its zoom 0 extent
// as meters per world unit.
#[test]
fn a_rotated_crs_measures_from_its_origin_with_y_down() {
    let world = rotated();
    for [lng, lat] in SAMPLES {
        let back = world.lat_lng_from_world(&world.world_from_lat_lng(&ll(lat, lng))).unwrap();
        assert_abs_diff_eq!(lng, back.longitude(), epsilon = 5e-11);
        assert_abs_diff_eq!(lat, back.latitude(), epsilon = 5e-11);
    }
    let location = lat_lng(&world, 0.25, 0.75);
    let position = rotate([location.longitude(), location.latitude()]);
    assert_abs_diff_eq!(-150.0 + 0.25 * 300.0, position[0], epsilon = 5e-11);
    assert_abs_diff_eq!(150.0 - 0.75 * 300.0, position[1], epsilon = 5e-11);
    assert_eq!(300.0, world.height_meters_per_world_unit(&lat_lng(&world, 0.5, 0.5)));
}

// Mercator written as a CRS projects and unprojects as Mercator does,
// and has its meters per world unit at the equator.
#[test]
fn mercator_written_as_a_crs_maps_as_mercator() {
    let world = mercator_as_crs();
    let mercator = WorldMapping::default();
    // Past its latitude limit, Mercator clamps the latitude.
    let within_limit = SAMPLES.into_iter().filter(|[_, lat]| lat.abs() <= LATITUDE_MAX);
    for [lng, lat] in within_limit.chain([[-180.0, -85.0], [180.0, 85.0]]) {
        let expected = mercator.world_from_lat_lng(&ll(lat, lng));
        let actual = world.world_from_lat_lng(&ll(lat, lng));
        assert_abs_diff_eq!(expected.x, actual.x, epsilon = 1e-12);
        assert_abs_diff_eq!(expected.y, actual.y, epsilon = 1e-12);
    }
    for [x, y] in [[0.5, 0.5], [0.1, 0.9], [0.999, 0.001], [0.25, 0.75]] {
        let expected = lat_lng(&mercator, x, y);
        let actual = lat_lng(&world, x, y);
        assert_abs_diff_eq!(expected.longitude(), actual.longitude(), epsilon = 5e-11);
        assert_abs_diff_eq!(expected.latitude(), actual.latitude(), epsilon = 5e-11);
    }
    let equator = ll(0.0, 0.0);
    assert_abs_diff_eq!(
        mercator.height_meters_per_world_unit(&equator),
        world.height_meters_per_world_unit(&equator),
        epsilon = 5e-7
    );
}

#[test]
fn a_north_polar_projection_stops_its_latitude_range_short_of_the_south_pole() {
    // The opposite pole projects to infinity: the range ends where the
    // meridian stretches ten times as much as at the north pole.
    let world = mapping(crs::north_polar_stereographic("test:polar"));
    assert_eq!([-53.0, 90.0], world.latitude_range());
    let world = mapping(crs::polar_stereographic("test:polar"));
    assert_eq!([-53.0, 90.0], world.latitude_range());
}

// A south polar CRS's latitude range runs from the near pole to where the
// meridian stretches ten times as much as at the center.
#[test]
fn a_south_polar_projection_stops_its_latitude_range_short_of_the_north_pole() {
    let Crs { converter: north, .. } = crs::polar_stereographic("test:north");
    let north = Arc::new(north);
    let forward = Arc::clone(&north);
    let world = mapping(crs(
        "test:south-polar",
        move |[lng, lat]| {
            let mut position = [[0.0; 2]];
            forward.forward(&[[lng, -lat]], &mut position);
            position[0]
        },
        move |position| {
            let mut lng_lat = [[0.0; 2]];
            north.inverse(&[position], &mut lng_lat);
            [lng_lat[0][0], -lng_lat[0][1]]
        },
        [-4_194_304.0, 4_194_304.0],
        8_388_608.0,
    ));
    assert_eq!([-90.0, 53.0], world.latitude_range());
}

#[test]
fn a_mercator_box_is_the_rectangle_of_its_corners() {
    let world = WorldMapping::default();
    let bounds = LatLngBounds::hull(ll(-10.0, -20.0), ll(30.0, 40.0));
    let southwest = world.world_from_lat_lng(&bounds.southwest());
    let northeast = world.world_from_lat_lng(&bounds.northeast());
    let world_box = world.lng_lat_box_to_world_box(&bounds);
    assert_eq!(Point::new(southwest.x, northeast.y), world_box.min);
    assert_eq!(Point::new(northeast.x, southwest.y), world_box.max);
}

#[test]
fn a_polar_cap_box_holds_its_parallel_around_the_pole() {
    // The corners of the cap north of 60 N are the pole, at the center of the
    // square, and one point on its edge, a circle around the pole.
    let world = mapping(crs::north_polar_stereographic("test:polar"));
    let radius = world.world_from_lat_lng(&ll(60.0, 0.0)).y - 0.5;
    let world_box = world.lng_lat_box_to_world_box(&LatLngBounds::hull(ll(60.0, -180.0), ll(90.0, 180.0)));
    for (inner, outer) in [(0.5 - radius, world_box.min.x), (0.5 - radius, world_box.min.y)] {
        assert!(outer <= inner && outer >= inner - 0.05 * radius, "{outer} around {inner}");
    }
    for (inner, outer) in [(0.5 + radius, world_box.max.x), (0.5 + radius, world_box.max.y)] {
        assert!(outer >= inner && outer <= inner + 0.05 * radius, "{outer} around {inner}");
    }
}

#[test]
fn mercator_wraps_and_spans_the_earth_up_to_its_latitude_limit() {
    let world = WorldMapping::default();
    assert!(world.wraps());
    assert_eq!("mercator", world.name());
    assert_eq!([-LATITUDE_MAX, LATITUDE_MAX], world.latitude_range());
    let extent = world.tile_matrix_set().extent_at_zoom0;
    assert_abs_diff_eq!(2.0 * std::f64::consts::PI * EARTH_RADIUS_M, extent, epsilon = 1e-6);
}

/// Web Mercator's conversions in closed forms other than the mapping's, to
/// check the mapping against.
mod formulas {
    use std::f64::consts::PI;

    use mln_style::constants::{DEGREES_MAX, LATITUDE_MAX, LONGITUDE_MAX, TILE_SIZE_D};
    use mln_style::geo::{LatLng, WrapMode};
    use mln_style::math::{clamp_f64, deg2rad, rad2deg};

    use crate::geo::constants::M2PI;

    /// The offset of the map that puts `center` in the middle of a view at
    /// `scale`.
    pub(super) fn center_offset(center: &LatLng, scale: f64) -> (f64, f64) {
        let world_size = scale * TILE_SIZE_D;
        let latitude = deg2rad(center.latitude());
        (-center.longitude() * (world_size / 360.0), world_size / M2PI * latitude.tan().asinh())
    }

    /// The center that the offset `x`, `y` puts in the middle of a view at
    /// `scale`.
    pub(super) fn center(x: f64, y: f64, scale: f64) -> LatLng {
        let world_size = scale * TILE_SIZE_D;
        LatLng::saturating(
            rad2deg(2.0 * (y / (world_size / M2PI)).exp().atan() - 0.5 * PI),
            -x / (world_size / 360.0),
            WrapMode::Unwrapped,
        )
    }

    /// The point of `lat_lng` in a world `scale` times the tile size wide,
    /// its latitude within the limit.
    pub(super) fn project(lat_lng: &LatLng, scale: f64) -> (f64, f64) {
        let latitude = clamp_f64(lat_lng.latitude(), -LATITUDE_MAX, LATITUDE_MAX);
        let k = scale * TILE_SIZE_D / DEGREES_MAX;
        (
            (LONGITUDE_MAX + lat_lng.longitude()) * k,
            (LONGITUDE_MAX - rad2deg((PI / 4.0 + latitude * PI / DEGREES_MAX).tan().ln())) * k,
        )
    }

    /// The latitude and longitude of the point `x`, `y` in a world `scale`
    /// times the tile size wide.
    pub(super) fn unproject(x: f64, y: f64, scale: f64) -> (f64, f64) {
        let world_size = scale * TILE_SIZE_D;
        let (x, y) = (x * DEGREES_MAX / world_size, y * DEGREES_MAX / world_size);
        (deg2rad(LONGITUDE_MAX - y).exp().atan() * DEGREES_MAX / PI - 90.0, x - LONGITUDE_MAX)
    }
}

/// Latitudes from pole to pole a twentieth of a degree apart, with
/// Mercator's latitude limit, latitudes just past it and near the poles, and
/// the centers of the camera's tests.
fn sweep_latitudes() -> impl Iterator<Item = f64> {
    (-1800..=1800).map(|step| f64::from(step) / 20.0).chain([
        LATITUDE_MAX,
        -LATITUDE_MAX,
        85.06,
        -85.06,
        89.999_999,
        -89.999_999,
        37.7749,
        -33.8688,
        79.5,
        1e-9,
    ])
}

/// Longitudes in and past the world copy from -180 to 180.
const SWEEP_LONGITUDES: [f64; 6] = [-200.0, -122.4194, 0.0, 12.5, 151.2093, 180.0];

/// Scales from below zoom 0, where only the globe goes, past the highest
/// zoom, and the scale of the world square, a tile wide.
fn sweep_scales() -> impl Iterator<Item = f64> {
    [-1.5, 0.0, 1.7, 3.5, 10.0, 12.5, 22.0, 25.5].into_iter().map(f64::exp2).chain([1.0 / TILE_SIZE_D])
}

/// Fails unless `actual` is within a few parts in 10^12 of `expected`, or
/// of `magnitude`, the size of the space they're in, if that is larger.
fn assert_close(expected: f64, actual: f64, magnitude: f64, what: &str, at: [f64; 3]) {
    let tolerance = 1e-12 * expected.abs().max(actual.abs()).max(magnitude).max(1.0);
    assert!(
        expected == actual || (expected - actual).abs() <= tolerance,
        "{what} at {at:?}: {expected:e} and {actual:e}"
    );
}

// Mercator puts the camera's center and finds it back as the camera's closed
// forms do, past the latitude limit too, as the globe's center and an
// unconstrained one go.
#[test]
fn mercator_converts_the_center_as_the_closed_forms_do() {
    use mln_style::geo::WrapMode;

    let mercator = WorldMapping::default();
    for scale in sweep_scales() {
        for longitude in SWEEP_LONGITUDES {
            for latitude in sweep_latitudes() {
                let at = [latitude, longitude, scale];
                let center = ll(latitude, longitude);
                let (x, y) = formulas::center_offset(&center, scale);
                let point = mercator.project_from_center(&center, scale);
                assert_close(x, -point.x, scale * TILE_SIZE_D, "x", at);
                assert_close(y, -point.y, scale * TILE_SIZE_D, "y", at);
                let expected = formulas::center(x, y, scale);
                let actual = mercator.unproject_from_center(&point, scale, WrapMode::Unwrapped);
                assert_abs_diff_eq!(expected.latitude(), actual.latitude(), epsilon = 1e-9);
                assert_abs_diff_eq!(expected.longitude(), actual.longitude(), epsilon = 1e-9);
                assert_abs_diff_eq!(latitude, actual.latitude(), epsilon = 1e-9);
            }
        }
    }
}

// Mercator projects and unprojects points as the closed forms do, and scales
// heights as `Projection` does.
#[test]
fn mercator_converts_points_as_the_closed_forms_do() {
    use mln_style::geo::WrapMode;

    let mercator = WorldMapping::default();
    for longitude in SWEEP_LONGITUDES {
        for latitude in sweep_latitudes() {
            let location = ll(latitude, longitude);
            let expected = Projection::meters_per_pixel_at_latitude(latitude, 0.0) * TILE_SIZE_D;
            assert_close(
                expected,
                mercator.height_meters_per_world_unit(&location),
                0.0,
                "height",
                [latitude, longitude, 0.0],
            );
        }
    }
    for scale in sweep_scales() {
        for longitude in SWEEP_LONGITUDES {
            for latitude in sweep_latitudes() {
                let at = [latitude, longitude, scale];
                let (x, y) = formulas::project(&ll(latitude, longitude), scale);
                let point = mercator.project(&ll(latitude, longitude), scale);
                assert_close(x, point.x, scale * TILE_SIZE_D, "x", at);
                assert_close(y, point.y, scale * TILE_SIZE_D, "y", at);
            }
        }
        // Points across the world square and past it on every side.
        let world_size = scale * TILE_SIZE_D;
        for column in -20..=40 {
            for row in -20..=40 {
                let place = [f64::from(column) / 20.0 + 0.012_3, f64::from(row) / 20.0 + 0.004_56];
                let (latitude, longitude) = formulas::unproject(place[0] * world_size, place[1] * world_size, scale);
                let point = Point::new(place[0] * world_size, place[1] * world_size);
                let actual = mercator.unproject(&point, scale, WrapMode::Unwrapped).unwrap();
                assert_abs_diff_eq!(latitude, actual.latitude(), epsilon = 1e-9);
                assert_abs_diff_eq!(longitude, actual.longitude(), epsilon = 1e-9);
                let mut lng_lat = [[0.0; 2]];
                mercator.lng_lats_from_world(&[place], &mut lng_lat);
                assert_abs_diff_eq!(latitude, lng_lat[0][1], epsilon = 1e-9);
                assert_abs_diff_eq!(longitude, lng_lat[0][0], epsilon = 1e-9);
            }
        }
    }
}

// A Mercator view keeps its center's offset and finds its center as the
// camera's closed forms do, and scales the heights it draws as `Projection`
// does, on the flat map and the globe.
#[test]
fn a_mercator_view_keeps_its_center() {
    use mln_style::geo::WrapMode;
    use mln_style::size::Size;
    use mln_style::types::{ProjectionDefinition, ProjectionType};

    use crate::camera::{Camera, LogicalExtent, MapView, ProjectionMode, Viewport, zoom_scale};

    for (projection, zoom) in [
        (ProjectionType::Mercator, 1.7),
        (ProjectionType::Mercator, 12.5),
        (ProjectionType::VerticalPerspective, 3.5),
        (ProjectionType::VerticalPerspective, 10.0),
    ] {
        for latitude in [-79.5, -33.8688, 0.0, 10.0, 37.7749, 79.5] {
            for longitude in [-200.0, -122.4194, 151.2093] {
                let at = [latitude, longitude, zoom];
                let center = ll(latitude, longitude);
                let view = MapView {
                    camera: Camera { center, zoom, fov: 36.87, ..Camera::default() },
                    extent: LogicalExtent::new(Size::new(512, 512), 1.0),
                    projection_mode: ProjectionMode::default(),
                    viewport: Viewport::default(),
                    projection: ProjectionDefinition::new(projection).into(),
                }
                .to_view()
                .unwrap();
                assert_eq!(projection == ProjectionType::VerticalPerspective, view.is_globe());
                let (x, y) = formulas::center_offset(&center, zoom_scale(zoom));
                assert_close(x, view.x(), zoom_scale(zoom) * TILE_SIZE_D, "x", at);
                assert_close(y, view.y(), zoom_scale(zoom) * TILE_SIZE_D, "y", at);
                let actual = view.center(WrapMode::Unwrapped);
                assert_abs_diff_eq!(latitude, actual.latitude(), epsilon = 1e-12);
                assert_abs_diff_eq!(longitude, actual.longitude(), epsilon = 1e-12);
                let meters = Projection::meters_per_pixel_at_latitude(latitude, view.zoom());
                assert_close(meters, view.meters_per_pixel(), 0.0, "meters per pixel", at);
            }
        }
    }
}

#[test]
fn mappings_are_equal_when_they_are_the_same_one() {
    let a = identity();
    assert_eq!(a, a.clone());
    assert_ne!(a, identity());
    assert_ne!(a, WorldMapping::default());
    assert_eq!(WorldMapping::default(), WorldMapping::default());
}

#[test]
fn a_world_that_doesnt_wrap_has_no_latitude_range() {
    let id = crate::tile::UnwrappedTileID::new(12, 758, 100);
    assert_eq!([0.0, 0.0], crate::geo::lat_range(&id, &identity()));
    // The same tile row in Mercator is past 84 N, where the shader divides
    // slopes by the cosine of the latitude.
    let mercator = crate::geo::lat_range(&id, &WorldMapping::default());
    assert!(mercator[1] > 84.0, "{mercator:?}");
    assert!(mercator[0] > mercator[1], "{mercator:?}");
}

// The bottom row's south edge is the world's, not its north edge again.
#[test]
fn a_tile_of_the_bottom_row_spans_to_the_worlds_south_edge() {
    let world = WorldMapping::default();
    let max = LATITUDE_MAX as f32;
    let whole = crate::geo::lat_range(&crate::tile::UnwrappedTileID::new(0, 0, 0), &world);
    assert_abs_diff_eq!(whole[0], max, epsilon = 1e-4);
    assert_abs_diff_eq!(whole[1], -max, epsilon = 1e-4);
    let south = crate::geo::lat_range(&crate::tile::UnwrappedTileID::new(1, 1, 1), &world);
    assert_abs_diff_eq!(south[0], 0.0, epsilon = 1e-4);
    assert_abs_diff_eq!(south[1], -max, epsilon = 1e-4);
}