mln-rs-map 0.0.13

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
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
// The C++ transition lambdas capture `this`. Here a command's frame function
// takes the state as an argument and returns the camera at its progress,
// which `apply_transitions` composes with the other commands' cameras.
//
// C++ calls its observer and each command's finish callback from inside the
// transform, and guards against callbacks that start or cancel commands
// meanwhile. The port queues them as `TransformEvent`s, which the owner
// drains once the call returns.

use std::f64::consts::PI;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use geometry::Point;
use mln_map_types::{
    AnimationOptions, CameraDelta, CameraError, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
    CameraVelocity, CenterAndBearing, ConstrainMode, FreeCameraOptions, GesturePhase, MomentumDecay,
    MomentumDecayModel, MomentumEasing, MomentumSnap, NorthOrientation, ProjectionMode, TransformState, TransitionEnd,
    TransitionOutcome, VerticalPerspectiveProjection, ViewportMode,
};
use mln_style_types::ProjectionDefinition;
use mln_util::UnitBezier;
use mln_util::constants::{DEFAULT_TRANSITION_EASE, M2PI, PITCH_MAX};
use mln_util::error::Error;
use mln_util::geo::{EdgeInsets, LatLng, LatLngBounds, ScreenCoordinate, WrapMode};
use mln_util::interpolate::interpolate;
use mln_util::logging::{Event, Log};
use mln_util::projection::Projection;
use mln_util::size::Size;
use mln_util::time::Instant;
use parking_lot::Mutex;

use crate::map_event::{CameraChange, CameraChangeMode, CameraChangeSource};

/// A frame time older than this is stale (see [`Transform::frame_time`]):
/// longer than a frame at 10 fps, so any host that draws sets a fresh one
/// first.
pub(crate) const STALE_FRAME_TIME: Duration = Duration::from_millis(100);

/// Converts the given angle (in radians) to be numerically close to the
/// anchor angle, allowing it to be interpolated properly without sudden
/// jumps.
fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
    if angle.is_nan() || anchor_angle.is_nan() {
        return 0.0;
    }

    angle = mln_math::wrap(angle, -PI, PI);
    if angle == -PI {
        angle = PI;
    }
    let diff = (angle - anchor_angle).abs();
    if (angle - M2PI - anchor_angle).abs() < diff {
        angle -= M2PI;
    }
    if (angle + M2PI - anchor_angle).abs() < diff {
        angle += M2PI;
    }

    angle
}

fn lat_lng(lat: f64, lon: f64) -> LatLng {
    // C++ constructs LatLng directly, which throws std::domain_error.
    LatLng::new(lat, lon).unwrap_or_else(|e| panic!("{e}"))
}

/// An animation frame's `EdgeInsets(top, left, bottom, right)`. C++ throws
/// `std::domain_error` for NaN (infinite insets interpolate to NaN) out of
/// the frame, and nothing catches it; the port logs it, and the frame keeps
/// the insets.
fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
    EdgeInsets::new(top, left, bottom, right).map_err(|e| Log::error(Event::General, &e.message)).ok()
}

/// An animation frame's `Projection::unproject`, which constructs a `LatLng`
/// and so can throw `std::domain_error` (NaN); handled as
/// [`frame_edge_insets`]: the frame keeps the center and zoom.
fn frame_unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
    Projection::unproject(p, scale, wrap_mode).map_err(|e| Log::error(Event::General, &e.message)).ok()
}

/// Formats `value` with six decimals, as `std::to_string(double)` does.
fn std_to_string(value: f64) -> String {
    format!("{value:.6}")
}

/// Identifies a camera command that the transform started, in the
/// [`TransformEvent::CommandEnded`] that reports its end. Each command the
/// transform starts gets its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CameraCommandId(u64);

/// How a camera command ended.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CommandEnd {
    pub command: CameraCommandId,
    /// The command's [`AnimationOptions::transition_id`].
    pub transition_id: Option<u64>,
    pub end: TransitionEnd,
}

/// What the transform reports, in order, for its owner to drain with
/// [`Transform::drain_events`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TransformEvent {
    CameraWillChange(CameraChange),
    CameraIsChanging,
    CameraDidChange(CameraChange),
    /// A command ended: every command ends exactly once, unless the
    /// transform is dropped with the command still running (see
    /// [`Transform::close`]).
    CommandEnded(CommandEnd),
}

/// A command's camera at an eased progress: every field set, except a
/// center or padding the frame could not compute (logged), which keeps the
/// current one.
type FrameFn = Box<dyn Fn(&TransformState, f64) -> CameraOptions>;
pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;

// `Transform::CameraField`.
const CENTER: u16 = 1 << 0;
const ZOOM: u16 = 1 << 1;
const BEARING: u16 = 1 << 2;
const PITCH: u16 = 1 << 3;
const PADDING: u16 = 1 << 4;
const ALTITUDE: u16 = 1 << 5;
const ROLL: u16 = 1 << 6;
const FOV: u16 = 1 << 7;

/// The fields a command sets.
fn camera_fields(camera: &CameraOptions) -> u16 {
    let field = |set: bool, field: u16| if set { field } else { 0 };
    field(camera.center.is_some(), CENTER)
        | field(camera.zoom.is_some(), ZOOM)
        | field(camera.bearing.is_some(), BEARING)
        | field(camera.pitch.is_some(), PITCH)
        | field(camera.padding.is_some(), PADDING)
        | field(camera.center_altitude.is_some(), ALTITUDE)
        | field(camera.roll.is_some(), ROLL)
        | field(camera.fov.is_some(), FOV)
}

/// One camera command.
struct Transition {
    /// Remaining property ownership; replacement removes fields from this
    /// mask.
    fields: u16,
    /// Replacing any coupled field relinquishes all coupled fields together.
    coupled_fields: u16,
    /// Properties classified as moving at command start; intersected with
    /// `fields` when reporting movement, so replaced properties no longer
    /// contribute. A momentum adds the fields its settling moves.
    moving_fields: u16,
    start: Instant,
    /// A momentum extends it for its settling.
    duration: Duration,
    animation: AnimationOptions,
    frame: FrameFn,
    anchor: Option<ScreenCoordinate>,
    anchor_lat_lng: LatLng,
    /// Set for a momentum, which moves the camera relative to where it
    /// stands instead of through `frame`.
    momentum: Option<MomentumState>,
    /// Why the command ends, once something other than time ends it:
    /// `Cancelled`, or `Replaced` when later commands took all its fields.
    /// Set through [`Transition::ended_by`], where cancellation wins.
    stopped: Option<TransitionOutcome>,
    /// What started the command, which the change that ends it reports.
    source: CameraChangeSource,
    /// The command whose end this transition's end reports, if any.
    command: Option<CameraCommandId>,
    /// For a gesture's momentum, the gesture's serial: its end ends the
    /// gesture, unless another one started since.
    gesture: Option<u64>,
}

impl Transition {
    /// A command without coupled fields, anchor, momentum, end to report or
    /// gesture.
    fn new(
        fields: u16,
        moving_fields: u16,
        start: Instant,
        duration: Duration,
        animation: &AnimationOptions,
        frame: FrameFn,
        source: CameraChangeSource,
    ) -> Transition {
        Transition {
            fields,
            coupled_fields: 0,
            moving_fields,
            start,
            duration,
            animation: *animation,
            frame,
            anchor: None,
            anchor_lat_lng: LatLng::default(),
            momentum: None,
            stopped: None,
            source,
            command: None,
            gesture: None,
        }
    }

    fn mode(&self) -> CameraChangeMode {
        if self.duration == Duration::ZERO { CameraChangeMode::Immediate } else { CameraChangeMode::Animated }
    }

    /// Records why the command stops: `Cancelled` or `Replaced`. A
    /// cancellation wins over a replacement, as the C API reports
    /// it.
    fn ended_by(&mut self, outcome: TransitionOutcome) {
        if self.stopped != Some(TransitionOutcome::Cancelled) {
            self.stopped = Some(outcome);
        }
    }

    /// How the command ended, with a momentum's leftover speed: why it
    /// stopped, else `Replaced` if later commands took every momentum part,
    /// else `Completed`.
    fn end(&self) -> TransitionEnd {
        let (velocity, momentum_replaced) =
            self.momentum.as_ref().map_or((CameraVelocity::default(), false), MomentumState::end);
        let outcome = self.stopped.unwrap_or(if momentum_replaced {
            TransitionOutcome::Replaced
        } else {
            TransitionOutcome::Completed
        });
        TransitionEnd { outcome, velocity, generation: 0 }
    }

    /// The elapsed share of the duration at `now`, in [0, 1]; 1 for an
    /// immediate command, or without a clock.
    fn progress(&self, now: Option<Instant>) -> f64 {
        let duration = self.duration;
        match now {
            Some(now) if !duration.is_zero() => {
                mln_math::clamp_f64(now.saturating_duration_since(self.start).div_duration_f64(duration), 0.0, 1.0)
            }
            _ => 1.0,
        }
    }

    /// The time since the command started, at `now`; zero before it, and
    /// `Duration::MAX` without a clock, which ends every command.
    fn elapsed(&self, now: Option<Instant>) -> Duration {
        now.map_or(Duration::MAX, |now| now.saturating_duration_since(self.start))
    }

    /// Whether the command's time has run out at `now`.
    fn has_run_out(&self, now: Option<Instant>) -> bool {
        now.is_none_or(|now| now >= self.start && self.elapsed(Some(now)) >= self.duration)
    }
}

/// `seconds` truncated to whole nanoseconds, as `duration_cast` does; `None`
/// when negative, NaN, or too long for a `Duration` made of nanoseconds. The
/// bound is exclusive because `u64::MAX` rounds up as a double.
fn nanos_from_secs(seconds: f64) -> Option<Duration> {
    (seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
}

/// How far one part of a momentum moves, over how long, and along which
/// curve.
#[derive(Clone, Copy, Default)]
struct Glide {
    distance: f64,
    duration: Duration,
    /// For friction, the decay rate per second.
    rate: f64,
    /// For an eased glide, the curve it follows.
    easing: Option<MomentumEasing>,
}

impl Glide {
    /// Plans a release at `speed`, or returns nothing when it doesn't move.
    fn plan(speed: f64, decay: &MomentumDecay) -> Option<Glide> {
        if speed.is_nan() || speed <= 0.0 || speed < decay.min_speed {
            return None;
        }
        let mut speed = f64::min(speed, decay.max_speed);
        let mut glide = Glide::default();
        let seconds;
        match decay.model {
            MomentumDecayModel::Friction => {
                let half_life = decay.half_life.as_secs_f64();
                if half_life.is_nan() || half_life <= 0.0 || decay.stop_speed.is_nan() || decay.stop_speed <= 0.0 {
                    return None;
                }
                glide.rate = std::f64::consts::LN_2 / half_life;
                speed = f64::min(speed, decay.stop_speed + glide.rate * decay.max_distance);
                if speed <= decay.stop_speed {
                    return None;
                }
                seconds = (speed / decay.stop_speed).ln() / glide.rate;
                glide.distance = (speed - decay.stop_speed) / glide.rate;
            }
            MomentumDecayModel::Ease => {
                glide.distance = f64::min(decay.distance, decay.max_distance);
                seconds = decay.duration.as_secs_f64();
                glide.easing = Some(decay.easing);
            }
        }
        // A glide too long for the clock doesn't move.
        if glide.distance.is_nan() || glide.distance <= 0.0 {
            return None;
        }
        glide.duration = nanos_from_secs(seconds).filter(|duration| !duration.is_zero())?;
        Some(glide)
    }

    /// The share of the distance covered after `elapsed`, from 0 to 1.
    fn progress(&self, elapsed: Duration) -> f64 {
        if elapsed >= self.duration {
            return 1.0;
        }
        if elapsed.is_zero() {
            return 0.0;
        }
        let t = elapsed.as_secs_f64();
        let total = self.duration.as_secs_f64();
        match self.easing {
            None => (-self.rate * t).exp_m1() / (-self.rate * total).exp_m1(),
            Some(easing) => bezier(&easing).solve(t / total, 1e-6),
        }
    }

    /// The share of the distance covered per second after `elapsed`.
    fn speed(&self, elapsed: Duration) -> f64 {
        if elapsed >= self.duration {
            return 0.0;
        }
        let t = elapsed.as_secs_f64();
        let total = self.duration.as_secs_f64();
        let Some(easing) = self.easing else {
            return self.rate * (-self.rate * t).exp() / -(-self.rate * total).exp_m1();
        };
        // The slope dy/dx of the curve, from its derivatives in its own
        // parameter, which starts just past 0 where both can be 0.
        let ease = bezier(&easing);
        let p = f64::max(ease.solve_curve_x(t / total, 1e-6), 1e-6);
        let cy = 3.0 * easing.y1;
        let by = 3.0 * (easing.y2 - easing.y1) - cy;
        let ay = 1.0 - cy - by;
        let dy = (3.0 * ay * p + 2.0 * by) * p + cy;
        let dx = ease.sample_curve_derivative_x(p);
        if dx > 0.0 { dy / dx / total } else { 0.0 }
    }
}

fn bezier(easing: &MomentumEasing) -> UnitBezier {
    UnitBezier::new(easing.x1, easing.y1, easing.x2, easing.y2)
}

/// One part of a running momentum.
#[derive(Clone, Copy, Default)]
struct MomentumPart {
    /// The fields that this part needs to keep moving or to settle.
    fields: u16,
    glide: Glide,
    /// The share of the distance already applied.
    applied: f64,
    moving: bool,
    /// Where the part may settle once it stops moving.
    snap: Option<MomentumSnap>,
    snap_pending: bool,
    /// The change that the settling makes, while it runs, when it started,
    /// and its eased share applied.
    snap_delta: Option<f64>,
    snap_start: Duration,
    snap_applied: f64,
}

impl MomentumPart {
    fn active(&self) -> bool {
        self.moving || self.snap_pending || self.snap_delta.is_some()
    }
}

// The scalar parts of a momentum, in `MomentumState::scalars`.
const MOMENTUM_ZOOM: usize = 0;
const MOMENTUM_BEARING: usize = 1;
const MOMENTUM_PITCH: usize = 2;

/// A momentum under way.
struct MomentumState {
    options: CameraMomentum,
    /// The pan's distance, with its direction.
    pan_total: ScreenCoordinate,
    pan: MomentumPart,
    /// The zoom, bearing and pitch parts, and each one's signed distance.
    scalars: [MomentumPart; 3],
    scalar_totals: [f64; 3],
    /// Whether another command took a field that a moving part needed.
    replaced: bool,
    /// When the last frame applied the momentum, from its start.
    elapsed: Duration,
}

impl MomentumState {
    fn anchor(&self, part: usize) -> Option<ScreenCoordinate> {
        match part {
            MOMENTUM_ZOOM => self.options.zoom_anchor,
            MOMENTUM_BEARING => self.options.bearing_anchor,
            _ => self.options.pitch_anchor,
        }
    }

    /// Stops the parts that lost a field they need, and returns the fields
    /// that the rest still need.
    fn retain(&mut self, owned: u16) -> u16 {
        let mut needed = 0;
        let mut replaced = false;
        for part in std::iter::once(&mut self.pan).chain(self.scalars.iter_mut()) {
            if !part.active() {
                continue;
            }
            if part.fields & owned != part.fields {
                replaced |= part.moving || part.snap_delta.is_some();
                part.moving = false;
                part.snap_pending = false;
                part.snap_delta = None;
                continue;
            }
            needed |= part.fields;
        }
        self.replaced |= replaced;
        needed
    }

    /// The speed of the parts still moving, as of the last frame, which left
    /// the camera where it stands, and whether another command stopped a
    /// part early by taking a field it needed.
    fn end(&self) -> (CameraVelocity, bool) {
        let mut velocity = CameraVelocity::default();
        if self.pan.moving {
            let share = self.pan.glide.speed(self.elapsed);
            velocity.pan = ScreenCoordinate::new(self.pan_total.x * share, self.pan_total.y * share);
        }
        let speed = |i: usize| {
            let part = &self.scalars[i];
            if part.moving { self.scalar_totals[i] * part.glide.speed(self.elapsed) } else { 0.0 }
        };
        velocity.zoom = speed(MOMENTUM_ZOOM);
        velocity.bearing = speed(MOMENTUM_BEARING);
        velocity.pitch = speed(MOMENTUM_PITCH);
        (velocity, self.replaced)
    }
}

/// The change that `snap` makes to `value`, or zero when it stays. A
/// circular value, the bearing, has its targets within one turn from the
/// offset, and takes the shorter way around to the nearest.
fn snap_delta(value: f64, snap: &MomentumSnap, circular: bool) -> f64 {
    if snap.spacing.is_nan() || snap.spacing <= 0.0 {
        return 0.0;
    }
    let delta = if circular {
        let turn = value - snap.offset - 360.0 * ((value - snap.offset) / 360.0).floor();
        let below = (turn / snap.spacing).floor() * snap.spacing;
        let above = f64::min(below + snap.spacing, 360.0);
        if turn - below <= above - turn { below - turn } else { above - turn }
    } else {
        // `f64::round` rounds halfway away from zero, as std::round does.
        snap.offset + ((value - snap.offset) / snap.spacing).round() * snap.spacing - value
    };
    if delta.abs() <= snap.tolerance { delta } else { 0.0 }
}

/// The value that a part of a momentum moves, for its snap.
fn momentum_value(state: &TransformState, part: usize) -> f64 {
    match part {
        MOMENTUM_ZOOM => state.get_zoom(),
        MOMENTUM_BEARING => -mln_math::rad2deg(state.get_bearing()),
        _ => mln_math::rad2deg(state.get_pitch()),
    }
}

/// The time of the latest frame that a map's host drew, which the map's
/// animations sample at and its camera commands start from (see
/// [`Transform::set_frame_time`]). A clone shares the clock, so the thread
/// that draws can set it while the map lives on another.
#[derive(Clone, Debug, Default)]
pub struct FrameClock(Arc<Mutex<Option<Instant>>>);

impl FrameClock {
    pub fn set(&self, time: Option<Instant>) {
        *self.0.lock() = time;
    }

    #[must_use]
    pub fn get(&self) -> Option<Instant> {
        *self.0.lock()
    }
}

pub struct Transform {
    state: TransformState,

    transitions: Vec<Transition>,
    /// What the transform reports, for [`Self::drain_events`].
    events: Vec<TransformEvent>,
    /// The command being started, which the transitions it starts report
    /// their end to (see [`Self::command`]), unless `silent`.
    command: Option<CameraCommandId>,
    /// Set while a command starts transitions whose ends another of its
    /// transitions reports: a delta's changes before its momentum.
    silent: bool,
    next_command: u64,
    /// The commands made of several transitions, whose end waits for the
    /// last of them.
    joint_ends: Vec<JointEnd>,
    /// What the commands being started come from: a command unless a gesture
    /// or a momentum starts them (see [`Self::with_source`]).
    source: CameraChangeSource,
    gesture: GestureState,
    /// The host's current frame time (see [`Self::set_frame_time`]).
    frame_time: FrameClock,
    projection_for_zoom: Option<ProjectionForZoomFn>,
    globe_free_bearing: bool,
    globe_drag_hold: Option<GlobeDragHold>,
}

/// A command made of several transitions, which ends once with the
/// outcome that covers them all: cancelled if any was, otherwise closed if
/// any was, otherwise replaced if any was.
struct JointEnd {
    command: CameraCommandId,
    remaining: u32,
    outcome: TransitionOutcome,
}

/// The location a drag on the globe holds under the cursor, from the step
/// that grabbed it. The next step carries the drag on if it starts where
/// that one ended, at `cursor` with the camera and the view as that step
/// left them; any other step grabs the location under where it starts.
#[derive(Clone, Copy, Debug)]
struct GlobeDragHold {
    location: LatLng,
    cursor: ScreenCoordinate,
    camera: CameraOptions,
    size: Size,
}

/// The gesture that camera deltas and updates with a phase make.
#[derive(Clone, Copy, Debug, Default)]
struct GestureState {
    /// Between its first `Begin` or `Update` and its `End` or `Cancel`.
    active: bool,
    /// Counts gestures, so that an earlier gesture's momentum doesn't end a
    /// later gesture.
    serial: u64,
    /// The fields the gesture changed (`ZOOM`, `BEARING`, `PITCH`), which
    /// alone may settle.
    changed: u16,
}

impl GestureState {
    /// Records the fields a gesture's change moves.
    fn change(&mut self, zoom: bool, bearing: bool, pitch: bool) {
        self.changed |=
            (if zoom { ZOOM } else { 0 }) | (if bearing { BEARING } else { 0 }) | (if pitch { PITCH } else { 0 });
    }

    /// Drops the snaps of the parts the gesture didn't change: only what it
    /// changed settles.
    fn mask_snaps(&self, momentum: &mut CameraMomentum) {
        if self.changed & ZOOM == 0 {
            momentum.zoom_snap = None;
        }
        if self.changed & BEARING == 0 {
            momentum.bearing_snap = None;
        }
        if self.changed & PITCH == 0 {
            momentum.pitch_snap = None;
        }
    }
}

impl Transform {
    #[must_use]
    pub fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
        Self::from_state(TransformState::new(constrain_mode, viewport_mode))
    }

    pub(crate) fn from_state(state: TransformState) -> Self {
        Transform {
            state,
            transitions: Vec::new(),
            events: Vec::new(),
            command: None,
            silent: false,
            next_command: 0,
            joint_ends: Vec::new(),
            source: CameraChangeSource::Command,
            gesture: GestureState::default(),
            frame_time: FrameClock::default(),
            projection_for_zoom: None,
            globe_free_bearing: false,
            globe_drag_hold: None,
        }
    }

    /// Drains what the transform reported since the last call, oldest
    /// first. The transform keeps its buffer for what it reports next.
    pub fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
        self.events.drain(..)
    }

    /// Whether the transform reported something that
    /// [`drain_events`](Self::drain_events) hasn't drained.
    pub fn has_events(&self) -> bool {
        !self.events.is_empty()
    }

    fn emit(&mut self, event: TransformEvent) {
        self.events.push(event);
    }

    // MARK: - Map View

    pub fn resize(&mut self, size: Size) -> Result<(), Error> {
        if size.is_empty() {
            return Err(Error::invalid_argument("failed to resize: size is empty"));
        }

        if self.state.get_size() == size {
            return Ok(());
        }

        self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
        self.state.set_size(size);
        let (scale, center) = self.state.constrain_screen(self.state.get_scale());
        if let Some(center) = center {
            // Turns out that if you resize during a transition any changes
            // made to the state will be ignored :( So if we have to constrain
            // because of a resize and a transition is in progress - cancel
            // the transition!
            if self.in_transition() {
                self.cancel_transitions();
            }

            // Setting x and y isn't enough to change the center: Cc and Bc
            // must change too, which setLatLngZoom does.
            let zoom = self.state.scale_zoom(scale);
            self.state.set_lat_lng_zoom(&center, zoom);
            self.emit(TransformEvent::CameraDidChange(CameraChange::default()));

            return Ok(());
        }
        self.constrain_position(scale);

        self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
        Ok(())
    }

    // MARK: - Camera

    /// Returns the current camera options.
    pub fn get_camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
        self.state.get_camera_options(padding)
    }

    /// Change any combination of center, zoom, bearing, and pitch, without a
    /// transition. Omitted options keep their current animations.
    pub fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
        self.command(|transform| transform.jump(camera))
    }

    fn jump(&mut self, camera: &CameraOptions) {
        // On the globe the zoom decides how close to a pole the center can be.
        // GL JS's jump bounds the center by the zoom it lands on, where its
        // ease bounds it by the zoom it starts from unless given one, so the
        // jump settles the zoom.
        if self.state.is_globe_rendering()
            && let Some(center) = camera.center
            && camera.zoom.is_none()
        {
            let zoom = self.get_zoom()
                + VerticalPerspectiveProjection::zoom_adjustment(
                    self.get_lat_lng(WrapMode::Wrapped).latitude(),
                    center.latitude(),
                );
            self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
            return;
        }
        self.ease_to(camera, &AnimationOptions::default());
    }

    /// Change any combination of center, zoom, bearing, pitch and edgeInsets,
    /// with a smooth animation between old and new values. Omitted options
    /// keep their current animations and timing.
    pub fn ease_to(&mut self, camera: &CameraOptions, animation: &AnimationOptions) -> CameraCommandId {
        self.command(|transform| transform.ease(camera, animation))
    }

    fn ease(&mut self, input_camera: &CameraOptions, animation: &AnimationOptions) {
        let mut camera = *input_camera;
        let globe = self.state.is_globe_rendering();

        let duration = animation.duration.unwrap_or(Duration::ZERO);
        if !globe
            && self.state.get_lat_lng_bounds() == LatLngBounds::default()
            && !self.is_gesture_in_progress()
            && duration != Duration::ZERO
            && animation.easing.is_none()
        {
            // A plain timed ease flies without the zoom-out. The flight's
            // ground speed rises and falls along its path even at a constant
            // zoom, so an ease given an easing interpolates instead, and
            // moves as that easing says, as GL JS's easeTo does.
            self.fly_to(&camera, animation, true);
            return;
        }

        let mut zoom = camera.zoom.unwrap_or(self.get_zoom());
        if camera.zoom.is_none()
            && let Some(center) = camera.center
            && globe
        {
            zoom += VerticalPerspectiveProjection::zoom_adjustment(
                self.get_lat_lng(WrapMode::Wrapped).latitude(),
                center.latitude(),
            );
        }
        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);

        let padding = camera.padding.unwrap_or(self.state.get_edge_insets());
        let mut start_lat_lng = self.get_lat_lng(WrapMode::Unwrapped);
        let unwrapped_lat_lng = camera.center.unwrap_or(start_lat_lng);
        // On the globe the ease heads for the center the zoom it was given
        // allows, or else the zoom it starts from, as GL JS's does; its last
        // frame is bounded by the zoom it ends on.
        let lat_lng_end = self.state.constrained_center(
            &if self.state.get_lat_lng_bounds() == LatLngBounds::default() {
                unwrapped_lat_lng.wrapped()
            } else {
                unwrapped_lat_lng
            },
            if camera.zoom.is_some() { zoom } else { self.get_zoom() },
        );

        let mut bearing = match camera.bearing {
            Some(b) => mln_math::deg2rad(-b),
            None => self.get_bearing(),
        };
        let mut pitch = match camera.pitch {
            Some(p) => mln_math::deg2rad(p),
            None => self.get_pitch(),
        };
        let mut fov = match camera.fov {
            Some(f) => mln_math::deg2rad(f),
            None => self.get_field_of_view(),
        };
        let center_alt = camera.center_altitude.unwrap_or(self.state.get_center_altitude());
        let roll = match camera.roll {
            Some(r) => mln_math::deg2rad(r),
            None => self.get_roll(),
        };

        if zoom.is_nan() || bearing.is_nan() || pitch.is_nan() || roll.is_nan() || fov.is_nan() {
            self.end_unstarted(animation, TransitionOutcome::Cancelled);
            return;
        }

        if self.state.get_lat_lng_bounds() == LatLngBounds::default() {
            if self.is_gesture_in_progress() {
                // If gesture in progress, we transfer the wrap rounds from the
                // end longitude into start, so the "scroll effect" of rounding
                // the world is the same while assuring the end longitude
                // remains wrapped.
                let wrap = unwrapped_lat_lng.longitude() - lat_lng_end.longitude();
                start_lat_lng = lat_lng(start_lat_lng.latitude(), start_lat_lng.longitude() - wrap);
            } else {
                // Find the shortest path otherwise.
                start_lat_lng.unwrap_for_shortest_path(&lat_lng_end);
            }
        }
        let start_center_alt = self.state.get_center_altitude();

        let start_point = Projection::project(&start_lat_lng, self.state.get_scale());
        let end_point = Projection::project(&lat_lng_end, self.state.get_scale());

        // Constrain camera options.
        // The target is drawn in the projection the style gives at its zoom,
        // which the animation may cross into.
        let target_globe = match &self.projection_for_zoom {
            Some(projection_for_zoom) => projection_for_zoom(zoom).transition_state() > 0.0,
            None => globe,
        };
        zoom = mln_math::clamp_f64(
            zoom,
            self.state.get_min_zoom_at_latitude_with(lat_lng_end.latitude(), target_globe),
            self.state.get_max_zoom(),
        );
        pitch = mln_math::clamp_f64(pitch, self.state.get_min_pitch(), self.state.get_max_pitch());
        fov = mln_math::clamp_f64(fov, self.state.get_min_field_of_view(), self.state.get_max_field_of_view());

        // Minimize rotation by taking the shorter path around the circle.
        bearing = normalize_angle(bearing, self.state.get_bearing());

        let start_zoom = self.state.get_zoom();
        let start_bearing = normalize_angle(self.state.get_bearing(), bearing);
        let start_pitch = self.state.get_pitch();
        let start_roll = self.state.get_roll();
        let start_fov = f64::from(self.state.get_field_of_view());
        let start_edge_insets = self.state.get_edge_insets();

        // On the globe the zoom is eased in equator terms so the planet holds
        // its size as the latitude changes, and the center moves the way GL
        // JS moves it: longitude paced at 1 / cos(latitude), sped up ahead of
        // a zoom in.
        let normalized_start_zoom = if globe {
            start_zoom + VerticalPerspectiveProjection::zoom_adjustment(start_lat_lng.latitude(), 0.0)
        } else {
            start_zoom
        };
        let normalized_zoom = if globe {
            zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
        } else {
            zoom
        };
        let final_scale = self.state.zoom_scale(normalized_zoom - normalized_start_zoom);
        let base = if normalized_zoom > normalized_start_zoom {
            f64::min(2.0, final_scale)
        } else {
            f64::max(0.5, final_scale)
        };
        let delta_latitude = if globe {
            VerticalPerspectiveProjection::difference_of_angles_degrees(
                start_lat_lng.latitude(),
                lat_lng_end.latitude(),
            )
        } else {
            0.0
        };
        let delta_longitude = if globe {
            VerticalPerspectiveProjection::difference_of_angles_degrees(
                start_lat_lng.longitude(),
                lat_lng_end.longitude(),
            )
        } else {
            0.0
        };
        let moves_around_anchor = camera.anchor.is_some() && camera.center.is_none();

        let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
            let (frame_lat_lng, frame_zoom) = if globe {
                // An anchor moves the center a frame at a time (see
                // apply_transitions), so it stays, and the zoom follows its
                // latitude to keep the planet's size.
                let mut frame_lat_lng =
                    if moves_around_anchor { state.get_lat_lng(WrapMode::Unwrapped) } else { lat_lng_end };
                let mut frame_zoom = zoom;
                if moves_around_anchor {
                    frame_zoom = interpolate(&normalized_start_zoom, &normalized_zoom, t)
                        + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude());
                } else if t < 1.0 {
                    let factor = t * base.powf(1.0 - t);
                    frame_lat_lng = VerticalPerspectiveProjection::interpolate_lat_lng(
                        &start_lat_lng,
                        delta_latitude,
                        delta_longitude,
                        factor,
                    )
                    .wrapped();
                    frame_zoom = if zoom == start_zoom {
                        start_zoom
                    } else {
                        interpolate(&normalized_start_zoom, &normalized_zoom, t)
                            + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude())
                    };
                }
                (Some(frame_lat_lng), frame_zoom)
            } else {
                let frame_point = interpolate(&start_point, &end_point, t);
                (
                    frame_unproject(&frame_point, state.zoom_scale(start_zoom), WrapMode::Unwrapped),
                    interpolate(&start_zoom, &zoom, t),
                )
            };
            CameraOptions {
                center: frame_lat_lng,
                zoom: Some(frame_zoom),
                center_altitude: Some(interpolate(&start_center_alt, &center_alt, t)),
                bearing: Some(-mln_math::rad2deg(mln_math::wrap(interpolate(&start_bearing, &bearing, t), -PI, PI))),
                padding: interpolate_edge_insets(&start_edge_insets, &padding, t),
                pitch: Some(mln_math::rad2deg(interpolate(&start_pitch, &pitch, t))),
                roll: Some(mln_math::rad2deg(interpolate(&start_roll, &roll, t))),
                fov: Some(mln_math::rad2deg(interpolate(&start_fov, &fov, t))),
                ..Default::default()
            }
        });

        // On the globe the zoom keeps the planet's size as the center's
        // latitude changes, and a zoom moves the center when it bounds it
        // closer to the equator, so an ease that moves the center sets both
        // (an anchored one gets its center from the anchor).
        let moves_center = input_camera.center.is_some() || lat_lng_end.wrapped() != start_lat_lng.wrapped();
        let fields = if globe && moves_around_anchor {
            CameraOptions { zoom: Some(zoom), ..*input_camera }
        } else if globe && moves_center {
            CameraOptions { center: Some(lat_lng_end), zoom: Some(zoom), ..*input_camera }
        } else {
            *input_camera
        };
        self.start_transition(&fields, animation, frame, duration, false);
    }

    /// This method implements an “optimal path” animation, as detailed in:
    ///
    /// Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and
    /// panning.” INFOVIS ’03. pp. 15–22.
    /// <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>.
    ///
    /// Where applicable, local variable documentation begins with the
    /// associated variable or function in van Wijk (2003).
    pub(crate) fn fly_to(
        &mut self,
        camera: &CameraOptions,
        animation: &AnimationOptions,
        linear_zoom_interpolation: bool,
    ) -> CameraCommandId {
        self.command(|transform| transform.fly(camera, animation, linear_zoom_interpolation))
    }

    fn fly(&mut self, input_camera: &CameraOptions, animation: &AnimationOptions, linear_zoom_interpolation: bool) {
        let mut camera = *input_camera;
        let globe = self.state.is_globe_rendering();

        let mut zoom = camera.zoom.unwrap_or(self.get_zoom());
        if camera.zoom.is_none()
            && let Some(center) = camera.center
            && globe
        {
            zoom += VerticalPerspectiveProjection::zoom_adjustment(
                self.get_lat_lng(WrapMode::Wrapped).latitude(),
                center.latitude(),
            );
        }
        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);

        let padding = camera.padding.unwrap_or(self.state.get_edge_insets());
        // As in easeTo, the globe's flight heads for the center the zoom it
        // was given, or else starts from, allows.
        let lat_lng_end = self.state.constrained_center(
            &camera.center.unwrap_or(self.get_lat_lng(WrapMode::Unwrapped)).wrapped(),
            if camera.zoom.is_some() { zoom } else { self.get_zoom() },
        );
        let center_alt = camera.center_altitude.unwrap_or(self.state.get_center_altitude());
        let mut bearing = match camera.bearing {
            Some(b) => mln_math::deg2rad(-b),
            None => self.get_bearing(),
        };
        let mut pitch = match camera.pitch {
            Some(p) => mln_math::deg2rad(p),
            None => self.get_pitch(),
        };
        let roll = match camera.roll {
            Some(r) => mln_math::deg2rad(r),
            None => self.get_roll(),
        };
        let mut fov = match camera.fov {
            Some(f) => mln_math::deg2rad(f),
            None => self.get_field_of_view(),
        };

        if zoom.is_nan()
            || bearing.is_nan()
            || pitch.is_nan()
            || roll.is_nan()
            || fov.is_nan()
            || self.state.get_size().is_empty()
        {
            self.end_unstarted(animation, TransitionOutcome::Cancelled);
            return;
        }

        // Determine endpoints.
        let mut start_lat_lng = self.get_lat_lng(WrapMode::Unwrapped).wrapped();
        start_lat_lng.unwrap_for_shortest_path(&lat_lng_end);
        let start_center_alt = self.state.get_center_altitude();

        let start_point = Projection::project(&start_lat_lng, self.state.get_scale());
        let end_point = Projection::project(&lat_lng_end, self.state.get_scale());

        // Constrain camera options.
        // The target is drawn in the projection the style gives at its zoom,
        // which the animation may cross into.
        let target_globe = match &self.projection_for_zoom {
            Some(projection_for_zoom) => projection_for_zoom(zoom).transition_state() > 0.0,
            None => globe,
        };
        zoom = mln_math::clamp_f64(
            zoom,
            self.state.get_min_zoom_at_latitude_with(lat_lng_end.latitude(), target_globe),
            self.state.get_max_zoom(),
        );
        pitch = mln_math::clamp_f64(pitch, self.state.get_min_pitch(), self.state.get_max_pitch());
        fov = mln_math::clamp_f64(fov, self.state.get_min_field_of_view(), self.state.get_max_field_of_view());

        // Minimize rotation by taking the shorter path around the circle.
        bearing = normalize_angle(bearing, self.state.get_bearing());
        let start_zoom = self.state.scale_zoom(self.state.get_scale());
        let start_bearing = normalize_angle(self.state.get_bearing(), bearing);
        let start_pitch = self.state.get_pitch();
        let start_roll = self.state.get_roll();
        let start_fov = f64::from(self.state.get_field_of_view());

        // w₀: Initial visible span, measured in pixels at the initial scale.
        // Known henceforth as a <i>screenful</i>.
        let size = self.state.get_size();
        let w0 = f64::max(
            f64::from(size.width) - padding.left - padding.right,
            f64::from(size.height) - padding.top - padding.bottom,
        );
        // The globe counts zoom in equator terms and distance along the
        // surface, so the arc is the same at any latitude.
        let normalized_start_zoom = if globe {
            start_zoom + VerticalPerspectiveProjection::zoom_adjustment(start_lat_lng.latitude(), 0.0)
        } else {
            start_zoom
        };
        let normalized_zoom = if globe {
            zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
        } else {
            zoom
        };
        // w₁: Final visible span, measured in pixels with respect to the
        // initial scale.
        let w1 = w0 / self.state.zoom_scale(normalized_zoom - normalized_start_zoom);
        // Length of the flight path as projected onto the ground plane,
        // measured in pixels from the world image origin at the initial scale.
        let u1 = if globe {
            VerticalPerspectiveProjection::surface_distance_pixels(
                Projection::world_size(self.state.get_scale()),
                start_lat_lng.latitude(),
                &start_lat_lng,
                &lat_lng_end,
            )
        } else {
            (end_point.x - start_point.x).hypot(end_point.y - start_point.y)
        };

        // ρ: The relative amount of zooming that takes place along the flight
        // path. A high value maximizes zooming for an exaggerated animation,
        // while a low value minimizes zooming for something closer to
        // easeTo().
        //
        // 1.42 is the average value selected by participants in the user
        // study in van Wijk (2003). A value of 6<sup>¼</sup> would be
        // equivalent to the root mean squared average velocity,
        // V<sub>RMS</sub>. A value of 1 produces a circular motion.
        let mut rho = 1.42;
        if globe {
            // GL JS: the arc may not dip below the map's or the flight's
            // minimum zoom, and that only ever lowers ρ.
            let floor_zoom =
                f64::max(animation.min_zoom.unwrap_or(self.state.get_min_zoom()), self.state.get_min_zoom());
            let normalized_floor_zoom = f64::min(
                f64::min(
                    floor_zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0),
                    normalized_start_zoom,
                ),
                normalized_zoom,
            );
            let min_zoom = mln_math::clamp_f64(
                normalized_floor_zoom + VerticalPerspectiveProjection::zoom_adjustment(0.0, lat_lng_end.latitude()),
                self.state.get_min_zoom_at_latitude(lat_lng_end.latitude()),
                self.state.get_max_zoom(),
            );
            let w_max = w0
                / self.state.zoom_scale(
                    min_zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
                        - normalized_start_zoom,
                );
            if u1 != 0.0 {
                rho = f64::min(rho, (w_max / u1 * 2.0).sqrt());
            }
        } else if animation.min_zoom.is_some() || linear_zoom_interpolation {
            // util::min(a, b, c) = min(a, min(b, c)), fmin on doubles
            let mut min_zoom =
                mln_math::fmin(animation.min_zoom.unwrap_or(start_zoom), mln_math::fmin(start_zoom, zoom));
            min_zoom = mln_math::clamp_f64(
                min_zoom,
                self.state.get_min_zoom_at_latitude(lat_lng_end.latitude()),
                self.state.get_max_zoom(),
            );
            // w<sub>m</sub>: Maximum visible span, measured in pixels with
            // respect to the initial scale.
            let w_max = w0 / self.state.zoom_scale(min_zoom - start_zoom);
            rho = if u1 == 0.0 { 1.0 } else { (w_max / u1 * 2.0).sqrt() };
        }
        // ρ²
        let rho2 = rho * rho;

        // rᵢ: Returns the zoom-out factor at one end of the animation.
        //
        // @param i 0 for the ascent or 1 for the descent.
        let r = |i: f64| -> f64 {
            // bᵢ
            let b = (w1 * w1 - w0 * w0 + if i == 0.0 { 1.0 } else { -1.0 } * rho2 * rho2 * u1 * u1)
                / (2.0 * if i == 0.0 { w0 } else { w1 } * rho2 * u1);
            ((b * b + 1.0).sqrt() - b).ln()
        };

        // r₀: Zoom-out factor during ascent.
        let r0 = if u1 == 0.0 { f64::INFINITY } else { r(0.0) }; // Silence division by 0 on sanitize bot.
        let r1 = if u1 == 0.0 { f64::INFINITY } else { r(1.0) };

        // When u₀ = u₁, the optimal path doesn’t require both ascent and
        // descent.
        let is_close = u1.abs() < 0.000_001 || !r0.is_finite() || !r1.is_finite();

        // w(s): Returns the visible span on the ground, measured in pixels
        // with respect to the initial scale.
        //
        // Assumes an angular field of view of 2 arctan ½ ≈ 53°.
        let w = move |s: f64| -> f64 {
            if is_close {
                ((if w1 < w0 { -1.0 } else { 1.0 }) * rho * s).exp()
            } else {
                r0.cosh() / (r0 + rho * s).cosh()
            }
        };
        // u(s): Returns the distance along the flight path as projected onto
        // the ground plane, measured in pixels from the world image origin at
        // the initial scale.
        let u = move |s: f64| -> f64 {
            if is_close { 0.0 } else { w0 * (r0.cosh() * (r0 + rho * s).tanh() - r0.sinh()) / rho2 / u1 }
        };
        // S: Total length of the flight path, measured in ρ-screenfuls.
        let total_s = if is_close { (w1 / w0).ln().abs() / rho } else { (r1 - r0) / rho };

        let duration = if let Some(duration) = animation.duration {
            duration
        } else {
            // V: Average velocity, measured in ρ-screenfuls per second.
            let mut velocity = 1.2;
            if let Some(v) = animation.velocity {
                velocity = v / rho;
            }
            // duration_cast<Duration>(duration<double>(S / velocity)). A
            // duration Duration can't hold jumps, as one past max_duration
            // does, rather than saturating to a flight that never ends.
            nanos_from_secs(total_s / velocity).unwrap_or_default()
        };
        let duration = match animation.max_duration {
            Some(max) if !linear_zoom_interpolation && duration > max => Duration::ZERO,
            _ => duration,
        };
        let start_scale = self.state.get_scale();
        let start_edge_insets = self.state.get_edge_insets();
        let delta_latitude = if globe {
            VerticalPerspectiveProjection::difference_of_angles_degrees(
                start_lat_lng.latitude(),
                lat_lng_end.latitude(),
            )
        } else {
            0.0
        };
        let delta_longitude = if globe {
            VerticalPerspectiveProjection::difference_of_angles_degrees(
                start_lat_lng.longitude(),
                lat_lng_end.longitude(),
            )
        } else {
            0.0
        };

        let frame: FrameFn = Box::new(move |state: &TransformState, k: f64| {
            // s: The distance traveled along the flight path, measured in
            // ρ-screenfuls.
            let s = k * total_s;
            let us = if k == 1.0 { 1.0 } else { u(s) };

            let (frame_lat_lng, frame_zoom) = if globe {
                let mut frame_lat_lng = lat_lng_end;
                let mut frame_zoom = zoom;
                if k < 1.0 {
                    frame_lat_lng = VerticalPerspectiveProjection::interpolate_lat_lng(
                        &start_lat_lng,
                        delta_latitude,
                        delta_longitude,
                        us,
                    )
                    .wrapped();
                    let frame_normalized_zoom = if linear_zoom_interpolation {
                        interpolate(&normalized_start_zoom, &normalized_zoom, k)
                    } else {
                        normalized_start_zoom + state.scale_zoom(1.0 / w(s))
                    };
                    frame_zoom = frame_normalized_zoom
                        + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude());
                    if frame_zoom.is_nan() {
                        frame_zoom = zoom;
                    }
                }
                (Some(frame_lat_lng), frame_zoom)
            } else {
                // Calculate the current point and zoom level along the flight
                // path.
                let frame_point = interpolate(&start_point, &end_point, us);
                let mut frame_zoom = if linear_zoom_interpolation {
                    interpolate(&start_zoom, &zoom, k)
                } else {
                    start_zoom + state.scale_zoom(1.0 / w(s))
                };

                // Zoom can be NaN if size is empty.
                if frame_zoom.is_nan() {
                    frame_zoom = zoom;
                }

                // Convert to geographic coordinates and set the new viewpoint.
                (frame_unproject(&frame_point, start_scale, WrapMode::Unwrapped), frame_zoom)
            };
            CameraOptions {
                center: frame_lat_lng,
                zoom: Some(frame_zoom),
                center_altitude: Some(interpolate(&start_center_alt, &center_alt, us)),
                bearing: Some(-mln_math::rad2deg(mln_math::wrap(interpolate(&start_bearing, &bearing, k), -PI, PI))),
                padding: interpolate_edge_insets(&start_edge_insets, &padding, k),
                pitch: Some(mln_math::rad2deg(interpolate(&start_pitch, &pitch, k))),
                roll: Some(mln_math::rad2deg(interpolate(&start_roll, &roll, k))),
                fov: Some(mln_math::rad2deg(interpolate(&start_fov, &fov, k))),
                ..Default::default()
            }
        });

        self.start_transition(input_camera, animation, frame, duration, !linear_zoom_interpolation);
    }

    // MARK: - Position

    /// Whether the globe is drawn on a sized screen, so screen points reach
    /// it. Before the first resize, screen-point gestures are Mercator's.
    fn globe_on_screen(&self) -> bool {
        self.state.is_globe_rendering() && !self.state.get_size().is_empty()
    }

    /// Pans the map by the given amount.
    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN
    /// or infinite offset.
    pub fn move_by(
        &mut self,
        offset: &ScreenCoordinate,
        animation: &AnimationOptions,
    ) -> Result<CameraCommandId, Error> {
        self.move_by_with_anchor(offset, None, animation)
    }

    /// Moves the map by `offset`. A drag on the globe turns the planet so
    /// that the location under `anchor` follows the cursor. With the bearing
    /// held, steps that follow one another, each starting at the `anchor` of
    /// the one before with the camera as it left it, hold the location the
    /// first of them grabbed, wherever
    /// [`VerticalPerspectiveProjection::drag_center_holding`] has a center
    /// that does. Fails as [`move_by`](Self::move_by) does.
    pub fn move_by_with_anchor(
        &mut self,
        offset: &ScreenCoordinate,
        anchor: Option<ScreenCoordinate>,
        animation: &AnimationOptions,
    ) -> Result<CameraCommandId, Error> {
        let mut moved = Ok(());
        let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
        moved.map(|()| command)
    }

    fn move_by_now(
        &mut self,
        offset: &ScreenCoordinate,
        anchor: Option<ScreenCoordinate>,
        animation: &AnimationOptions,
    ) -> Result<(), Error> {
        let flipped = |state: &TransformState, point: &ScreenCoordinate| {
            ScreenCoordinate::new(point.x, f64::from(state.get_size().height) - point.y)
        };
        let size = self.state.get_size();
        let view_center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
        let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
        let globe = self.globe_on_screen();
        if globe && (offset.x.is_nan() || offset.y.is_nan()) {
            return Err(Error::invalid_argument("offset must not be NaN"));
        }
        if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
            return Err(Error::invalid_argument("offset must not be infinite"));
        }
        if globe
            && let Some(duration) = fling_duration
            && self.globe_free_bearing
        {
            // A fling with the bearing free turns the planet on about the axis
            // the drag turned it about, so it carries on over a pole instead
            // of spinning round it.
            let start = CenterAndBearing {
                center: self.get_lat_lng(WrapMode::Unwrapped),
                bearing: -mln_math::rad2deg(self.get_bearing()),
            };
            let end = VerticalPerspectiveProjection::fling_camera(
                &self.state,
                &flipped(&self.state, &view_center),
                &ScreenCoordinate::new(offset.x, -offset.y),
            );
            let start_zoom = self.get_zoom();
            let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
                let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
                let center = state.constrained_center(&camera.center, state.get_zoom());
                CameraOptions {
                    center: Some(center),
                    zoom: Some(
                        start_zoom
                            + VerticalPerspectiveProjection::zoom_adjustment(
                                start.center.latitude(),
                                center.latitude(),
                            ),
                    ),
                    bearing: Some(camera.bearing),
                    ..Default::default()
                }
            });
            // The fling sets the center, the zoom that keeps the planet's
            // size and the bearing.
            let fields = CameraOptions {
                center: Some(end.center),
                zoom: Some(start_zoom),
                bearing: Some(end.bearing),
                ..Default::default()
            };
            self.start_transition(&fields, animation, frame, duration, false);
            return Ok(());
        }

        if globe && fling_duration.is_some() {
            // An animated move, a fling, turns the globe as GL JS's inertia
            // does: the location under the far end of a long one can be off
            // the planet or over a pole. It stops short of half a turn, which
            // the ease would take the other way round.
            let mut center = self
                .state
                .constrained_center(&VerticalPerspectiveProjection::pan_center(&self.state, offset), self.get_zoom());
            let longitude = self.get_lat_lng(WrapMode::Unwrapped).longitude();
            if (center.longitude() - longitude).abs() > 180.0 {
                center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
            }
            self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
            return Ok(());
        }

        if globe {
            // A drag turns the globe as GL JS's does: one rotation that brings
            // the location under the cursor back under it with the bearing
            // held, around the cursor when it is on the planet and around the
            // center otherwise. With a free bearing the rotation turns the
            // bearing too, so the location stays under the cursor.
            //
            // With the bearing held, that rotation loses the turn it would
            // give the bearing, so step after step the location slips from
            // under the cursor. Where a center holds it there exactly, the
            // drag takes that center instead, for the location its first step
            // grabbed. A step the exact center isn't for doesn't hold: the
            // step after it grabs anew, so the drag goes from one way to the
            // other without a jump.
            let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
                VerticalPerspectiveProjection::screen_coordinate_hits_globe(state, &flipped(state, point))
            };
            let grab = match anchor {
                Some(anchor) if on_globe(&self.state, &anchor) => anchor,
                _ => view_center,
            };
            let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
            let mut camera = CameraOptions::default();
            let held = self.globe_drag_hold.take();
            let hold = match anchor {
                Some(anchor) if !self.globe_free_bearing && on_globe(&self.state, &anchor) => {
                    let from = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
                    let location = match held {
                        Some(held)
                            if (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3
                                && held.size == size
                                && held.camera == self.get_camera_options(None) =>
                        {
                            Some(held.location)
                        }
                        _ if on_globe(&self.state, &from) => self
                            .state
                            .screen_coordinate_to_lat_lng(&flipped(&self.state, &from), WrapMode::Unwrapped)
                            .ok(),
                        _ => None,
                    };
                    location.and_then(|location| {
                        VerticalPerspectiveProjection::drag_center_holding(
                            &self.state,
                            &location,
                            &flipped(&self.state, &anchor),
                        )
                        .map(|center| (location, anchor, center))
                    })
                }
                _ => None,
            };
            let mut center = if let Some((_, _, center)) = hold {
                center
            } else if self.globe_free_bearing {
                let drag =
                    VerticalPerspectiveProjection::drag_camera(&self.state, &flipped(&self.state, &grab), &pan_delta);
                camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
                drag.center
            } else {
                VerticalPerspectiveProjection::drag_center(&self.state, &flipped(&self.state, &grab), &pan_delta)
            };
            center = self.state.constrained_center(&center, self.get_zoom());
            let zoom = self.get_zoom()
                + VerticalPerspectiveProjection::zoom_adjustment(
                    self.get_lat_lng(WrapMode::Wrapped).latitude(),
                    center.latitude(),
                );
            self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
            self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
                location,
                cursor,
                camera: self.get_camera_options(None),
                size,
            });
            return Ok(());
        }

        let mut center_offset = *offset;

        // Reduce the offset so that it never goes past the horizon. If it
        // goes past the horizon, the pan direction is opposite of the
        // intended direction.
        let pitch = self.state.get_pitch();
        let offset_length = offset.x.hypot(offset.y);
        if pitch > 0.0 && offset_length > 0.0 {
            let camera_to_center =
                0.5 * f64::from(self.state.get_size().height) / (f64::from(self.state.get_field_of_view()) / 2.0).tan();
            let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
            // must be < 1 to keep the offset short of the horizon
            let horizon_factor = 0.75;
            let scale = pixels_to_horizon * horizon_factor / offset_length;
            if scale < 1.0 {
                center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
            }
        }

        let size = self.state.get_size();
        let center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
        let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
        // Use unwrapped LatLng to carry information about moveBy direction.
        let center = self.screen_coordinate_to_lat_lng(&point_on_screen, WrapMode::Unwrapped)?;
        self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
        Ok(())
    }

    pub fn get_lat_lng(&self, wrap: WrapMode) -> LatLng {
        self.state.get_lat_lng(wrap)
    }

    // MARK: - Zoom

    pub(crate) fn get_zoom(&self) -> f64 {
        self.state.get_zoom()
    }

    // MARK: - Bounds

    pub fn set_lat_lng_bounds(&mut self, bounds: LatLngBounds) -> Result<(), Error> {
        if !bounds.valid() {
            return Err(Error::invalid_argument("failed to set bounds: bounds are invalid"));
        }
        self.state.set_lat_lng_bounds(bounds);
        Ok(())
    }

    pub(crate) fn set_min_zoom(&mut self, min_zoom: f64) {
        if min_zoom.is_nan() {
            return;
        }
        self.state.set_min_zoom(min_zoom);
    }

    pub(crate) fn set_max_zoom(&mut self, max_zoom: f64) {
        if max_zoom.is_nan() {
            return;
        }
        self.state.set_max_zoom(max_zoom);
    }

    pub(crate) fn set_min_pitch(&mut self, min_pitch: f64) {
        if min_pitch.is_nan() {
            return;
        }
        if mln_math::deg2rad(min_pitch) < mln_util::constants::PITCH_MIN {
            Log::warning(
                Event::General,
                format!(
                    "Trying to set minimum pitch below the limit ({} degrees), the value will be clamped.",
                    std_to_string(mln_math::rad2deg(mln_util::constants::PITCH_MIN))
                ),
            );
        }
        self.state.set_min_pitch(mln_math::deg2rad(min_pitch));
    }

    pub fn set_max_pitch(&mut self, max_pitch: f64) {
        if max_pitch.is_nan() {
            return;
        }
        if mln_math::deg2rad(max_pitch) > PITCH_MAX {
            Log::warning(
                Event::General,
                format!(
                    "Trying to set maximum pitch above the limit ({} degrees), the value will be clamped.",
                    std_to_string(mln_math::rad2deg(PITCH_MAX))
                ),
            );
        }
        self.state.set_max_pitch(mln_math::deg2rad(max_pitch));
    }

    pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
        self.state.set_frustum_offset(frustum_offset);
    }

    // MARK: - Bearing

    pub(crate) fn get_bearing(&self) -> f64 {
        self.state.get_bearing()
    }

    // MARK: - Pitch

    pub fn get_pitch(&self) -> f64 {
        self.state.get_pitch()
    }

    pub(crate) fn get_roll(&self) -> f64 {
        self.state.get_roll()
    }

    /// Returns `state.getFieldOfView()` (a float) as double.
    pub(crate) fn get_field_of_view(&self) -> f64 {
        f64::from(self.state.get_field_of_view())
    }

    // MARK: - Projection

    pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
        self.state.set_projection_definition(definition);
    }

    /// The projection the style gives at a zoom, which constrains an
    /// animation's target as it constrains a jump.
    pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
        self.projection_for_zoom = projection_for_zoom;
    }

    pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
        self.globe_free_bearing = free_bearing;
    }

    pub(crate) fn is_globe_free_bearing(&self) -> bool {
        self.globe_free_bearing
    }

    #[cfg(test)]
    pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
        self.state.is_location_occluded(lat_lng)
    }

    // MARK: - North Orientation

    pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
        self.state.set_north_orientation(orientation);
        self.constrain_position(self.state.get_scale());
    }

    /// Moves the state to the position nearest its own at `scale` that the
    /// constrain mode allows.
    fn constrain_position(&mut self, scale: f64) {
        let (scale, x, y) = self.state.constrain(scale, self.state.get_x(), self.state.get_y());
        self.state.set_x(x);
        self.state.set_y(y);
        self.state.set_scale(scale);
    }

    // MARK: - Constrain mode

    pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
        self.state.set_constrain_mode(mode);
        self.constrain_position(self.state.get_scale());
    }

    // MARK: - Viewport mode

    pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
        self.state.set_viewport_mode(mode);
    }

    // MARK: - Projection mode

    pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
        if let Some(x_skew) = options.x_skew {
            self.state.set_x_skew(x_skew);
        }
        if let Some(y_skew) = options.y_skew {
            self.state.set_y_skew(y_skew);
        }
        if let Some(axonometric) = options.axonometric {
            self.state.set_axonometric(axonometric);
        }
    }

    #[cfg(test)]
    pub(crate) fn get_projection_mode(&self) -> ProjectionMode {
        ProjectionMode::default()
            .with_axonometric(self.state.get_axonometric())
            .with_x_skew(self.state.get_x_skew())
            .with_y_skew(self.state.get_y_skew())
    }

    // MARK: - Transition

    /// Starts one camera command. `camera` is the command as given: the
    /// fields it sets are the fields it takes over from the running
    /// commands. A flight couples center and zoom; an anchored command
    /// couples center with its fields. Replacing any field of a coupled
    /// group stops the whole group, and a command left with no fields
    /// finishes.
    fn start_transition(
        &mut self,
        camera: &CameraOptions,
        animation: &AnimationOptions,
        frame: FrameFn,
        duration: Duration,
        flight: bool,
    ) {
        let mut fields = camera_fields(camera);
        let mut coupled_fields = if flight { CENTER | ZOOM } else { 0 };
        fields |= coupled_fields;

        // An anchor controls center together with the properties it
        // transforms. An explicit center takes precedence over an anchor.
        let mut anchor = if camera.center.is_some() { None } else { camera.anchor };
        let mut anchor_lat_lng = LatLng::default();
        if let Some(a) = anchor.as_mut() {
            a.y = f64::from(self.state.get_size().height) - a.y;
            // C++ throws std::domain_error out of the camera change for an
            // anchor that has no LatLng (NaN or infinite); the port logs it
            // and ignores the anchor.
            match self.state.screen_coordinate_to_lat_lng(a, WrapMode::Unwrapped) {
                Ok(lat_lng) => {
                    anchor_lat_lng = lat_lng;
                    fields |= CENTER;
                    coupled_fields = fields;
                }
                Err(e) => {
                    Log::error(Event::General, &e.message);
                    anchor = None;
                }
            }
        }

        let target = frame(&self.state, 1.0);
        let panning = flight || anchor.is_some() || camera.center != Some(self.get_lat_lng(WrapMode::Unwrapped));
        let scaling = flight || target.zoom != Some(self.get_zoom());
        let rotating = target.bearing != Some(-mln_math::rad2deg(self.get_bearing()));
        let moving_fields = (if panning { CENTER } else { 0 })
            | (if scaling { ZOOM } else { 0 })
            | (if rotating { BEARING } else { 0 });

        let start = self.now();
        let duration = if fields != 0 { duration } else { Duration::ZERO };
        let transition = Transition {
            coupled_fields,
            anchor,
            anchor_lat_lng,
            command: self.reporting(),
            ..Transition::new(fields, moving_fields, start, duration, animation, frame, self.source)
        };
        let mode = transition.mode();

        let finished = self.release_fields(fields);
        self.transitions.push(transition);
        self.update_movement_flags();
        self.finish_transitions(finished);

        self.emit(TransformEvent::CameraWillChange(CameraChange { mode, source: self.source }));

        if duration == Duration::ZERO {
            let index = self.transitions.len() - 1;
            self.apply_transitions(Some(index), Some(start));
            let transition = self.transitions.remove(index);
            self.update_movement_flags();
            self.finish_transitions(vec![transition]);
        }
    }

    /// Composes the current camera with the camera of each running command
    /// that isn't a momentum, or only of the one at `only`, at `now`, for
    /// the fields it still owns, then applies the result.
    fn apply_transitions(&mut self, only: Option<usize>, now: Option<Instant>) {
        // The center is unwrapped, or wrapped on the globe without bounds
        // (TransformState::get_camera_options).
        let current = self.state.get_camera_options(None);
        let mut camera = current;

        let active = match only {
            Some(index) => &self.transitions[index..=index],
            None => &self.transitions[..],
        };
        for transition in active {
            if transition.momentum.is_some() {
                continue;
            }
            let t = transition.progress(now);
            let ease = transition.animation.easing.unwrap_or(DEFAULT_TRANSITION_EASE);
            let value = (transition.frame)(&self.state, if t == 1.0 { 1.0 } else { ease.solve(t, 0.001) });
            let fields = transition.fields;
            // A frame without a center or padding (see FrameFn) keeps the
            // current one.
            if fields & CENTER != 0 && value.center.is_some() {
                camera.center = value.center;
            }
            if fields & ZOOM != 0 {
                camera.zoom = value.zoom;
            }
            if fields & BEARING != 0 {
                camera.bearing = value.bearing;
            }
            if fields & PITCH != 0 {
                camera.pitch = value.pitch;
            }
            if fields & PADDING != 0 && value.padding.is_some() {
                camera.padding = value.padding;
            }
            if fields & ALTITUDE != 0 {
                camera.center_altitude = value.center_altitude;
            }
            if fields & ROLL != 0 {
                camera.roll = value.roll;
            }
            if fields & FOV != 0 {
                camera.fov = value.fov;
            }
        }

        // An active anchor also applies to immediate changes of other
        // properties.
        let anchored = self.transitions.iter().rev().find_map(|transition| {
            let anchor = transition.anchor.filter(|_| transition.fields & CENTER != 0)?;
            Some((anchor, transition.anchor_lat_lng))
        });

        // On the globe the anchor is re-read every frame and the zoom around
        // it is GL JS's blend of the exact solution and a damped heuristic;
        // the exact solution alone jumps near the horizon. A frame can't
        // return the C++ exception for an anchor with no LatLng; it is
        // logged, and the anchor's location at the start stands in.
        let globe_zoom_around = match anchored {
            Some((anchor, anchor_lat_lng)) if self.globe_on_screen() => {
                let location =
                    self.state.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped).unwrap_or_else(|e| {
                        Log::error(Event::General, &e.message);
                        anchor_lat_lng
                    });
                Some((location, self.state.get_zoom()))
            }
            _ => None,
        };

        // Compose the camera before applying constraints. In particular,
        // padding and field of view determine the pitch limit, and center
        // and zoom jointly determine the geographic bounds and altitude
        // scale.
        //
        // C++ sets every angle from its degrees. The port leaves the angles
        // no command changed as they are, so that converting them to degrees
        // and back doesn't move them.
        let padding = camera.padding.unwrap_or_default();
        self.state.set_edge_insets(&padding);
        if let Some(fov) = camera.fov.filter(|_| camera.fov != current.fov) {
            self.state.set_field_of_view(mln_math::deg2rad(fov));
        }
        if let Some(bearing) = camera.bearing.filter(|_| camera.bearing != current.bearing) {
            self.state.set_bearing(mln_math::deg2rad(-bearing));
        }
        if let Some(roll) = camera.roll.filter(|_| camera.roll != current.roll) {
            self.state.set_roll(mln_math::deg2rad(roll));
        }
        let pitch = match camera.pitch.filter(|_| camera.pitch != current.pitch) {
            Some(pitch) => mln_math::deg2rad(pitch),
            None => self.state.get_pitch(),
        };
        self.state.set_pitch(f64::min(get_max_pitch_for_edge_insets(&self.state, &padding), pitch));
        let mut zoom = camera.zoom.unwrap_or_default();
        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
        self.state.set_lat_lng_zoom(&camera.center.unwrap_or_default(), zoom);
        if let Some((anchor, anchor_lat_lng)) = anchored {
            match globe_zoom_around {
                Some((location, zoom_before)) if self.state.get_zoom() != zoom_before => {
                    let zoom_delta = self.state.get_zoom() - zoom_before;
                    VerticalPerspectiveProjection::zoom_around_point(
                        &mut self.state,
                        &anchor,
                        &location,
                        zoom_delta,
                        self.globe_free_bearing,
                    );
                }
                // The anchor had a LatLng at the start; a frame can't return
                // the C++ exception, so it is logged, as in frame_edge_insets.
                _ => {
                    if let Err(e) = self.state.move_lat_lng(&anchor_lat_lng, &anchor) {
                        Log::error(Event::General, &e.message);
                    }
                }
            }
        }
        self.state.set_center_altitude(camera.center_altitude.unwrap_or_default());
    }

    /// Reports the fields the running commands move as the state's panning,
    /// scaling and rotating flags.
    fn update_movement_flags(&mut self) {
        let moving = self.transitions.iter().fold(0, |moving, t| moving | (t.fields & t.moving_fields));
        self.state.set_panning_in_progress(moving & CENTER != 0);
        self.state.set_scaling_in_progress(moving & ZOOM != 0);
        self.state.set_rotating_in_progress(moving & BEARING != 0);
    }

    fn finish_transitions(&mut self, finished: Vec<Transition>) {
        for transition in finished {
            self.end_gesture_momentum(transition.gesture);
            self.report_end(transition.command, transition.animation.transition_id, transition.end());
            // This notification ends a command, not necessarily all camera
            // motion.
            let change = CameraChange { mode: transition.mode(), source: transition.source };
            self.emit(TransformEvent::CameraDidChange(change));
        }
    }

    /// Whether any camera command is still animating.
    pub fn in_transition(&self) -> bool {
        !self.transitions.is_empty()
    }

    /// Moves the camera to where its commands are at `now`, and ends the
    /// ones that have run out; `None`, for a map without a clock, ends them all.
    pub fn update_transitions(&mut self, now: Option<Instant>) {
        if self.transitions.is_empty() {
            return;
        }

        if self.transitions.iter().any(|t| t.momentum.is_none()) {
            self.apply_transitions(None, now);
        }
        for index in 0..self.transitions.len() {
            self.advance_momentum(index, now);
        }

        let finished: Vec<_> = self.transitions.extract_if(.., |t| t.has_run_out(now) || t.fields == 0).collect();
        self.update_movement_flags();
        if !self.transitions.is_empty() {
            self.emit(TransformEvent::CameraIsChanging);
        }

        self.finish_transitions(finished);
    }

    /// Takes `fields` from the running commands, and returns the ones left
    /// with no fields, which the caller finishes.
    fn release_fields(&mut self, fields: u16) -> Vec<Transition> {
        for active in &mut self.transitions {
            let mut replaced = fields;
            if active.coupled_fields & replaced != 0 {
                replaced |= active.coupled_fields;
            }
            active.fields &= !replaced;
            if let Some(momentum) = &mut active.momentum {
                active.fields = momentum.retain(active.fields);
            }
            if active.fields == 0 {
                active.ended_by(TransitionOutcome::Replaced);
            }
        }
        self.transitions.extract_if(.., |active| active.fields == 0).collect()
    }

    // MARK: - Commands and their ends

    /// Runs `start` as a camera command, and returns the command. The
    /// transitions that `start` starts report their end to it, as does a
    /// command that fails or has nothing to move. Within a command being
    /// started, `start` is part of that command.
    fn command(&mut self, start: impl FnOnce(&mut Self)) -> CameraCommandId {
        if let Some(command) = self.command {
            start(self);
            return command;
        }
        let command = CameraCommandId(self.next_command);
        self.next_command += 1;
        self.command = Some(command);
        start(self);
        self.command = None;
        command
    }

    /// The command that the transitions being started report their end to.
    fn reporting(&self) -> Option<CameraCommandId> {
        self.command.filter(|_| !self.silent)
    }

    /// Makes the command being started end once, when `count` of its ends
    /// have been reported.
    fn join_ends(&mut self, count: u32) {
        if let Some(command) = self.reporting().filter(|_| count > 1) {
            self.joint_ends.push(JointEnd { command, remaining: count, outcome: TransitionOutcome::Completed });
        }
    }

    /// Reports an end of `command`, which ends it unless it waits for more
    /// (see [`Self::join_ends`]).
    fn report_end(&mut self, command: Option<CameraCommandId>, transition_id: Option<u64>, mut end: TransitionEnd) {
        let Some(command) = command else { return };
        if let Some(index) = self.joint_ends.iter().position(|joint| joint.command == command) {
            let joint = &mut self.joint_ends[index];
            joint.remaining -= 1;
            joint.outcome = match (joint.outcome, end.outcome) {
                (TransitionOutcome::Cancelled, _) | (_, TransitionOutcome::Cancelled) => TransitionOutcome::Cancelled,
                (TransitionOutcome::Closed, _) | (_, TransitionOutcome::Closed) => TransitionOutcome::Closed,
                (TransitionOutcome::Replaced, _) | (_, TransitionOutcome::Replaced) => TransitionOutcome::Replaced,
                _ => TransitionOutcome::Completed,
            };
            if joint.remaining > 0 {
                return;
            }
            end.outcome = joint.outcome;
            self.joint_ends.swap_remove(index);
        }
        self.emit(TransformEvent::CommandEnded(CommandEnd { command, transition_id, end }));
    }

    /// Ends a command that started no transition: one that failed before it
    /// moved the camera, or a momentum with nothing to move.
    fn end_unstarted(&mut self, animation: &AnimationOptions, outcome: TransitionOutcome) {
        self.report_end(
            self.reporting(),
            animation.transition_id,
            TransitionEnd { outcome, ..TransitionEnd::default() },
        );
    }

    // MARK: - Momentum

    /// Continues a gesture with momentum. The momentum replaces the running
    /// animations of the fields that it moves, as a camera command does.
    #[cfg(test)]
    pub(crate) fn start_momentum(&mut self, options: &CameraMomentum, animation: &AnimationOptions) -> CameraCommandId {
        self.command(|transform| {
            transform.with_source(CameraChangeSource::Momentum, |transform| {
                transform.start_momentum_now(options, animation, None);
            });
        })
    }

    /// Starts a momentum; `gesture` is the serial of the gesture it
    /// continues, which ends with it.
    fn start_momentum_now(&mut self, options: &CameraMomentum, animation: &AnimationOptions, gesture: Option<u64>) {
        let momentum_change = |mode: CameraChangeMode| CameraChange { mode, source: CameraChangeSource::Momentum };
        let mut momentum = MomentumState {
            options: *options,
            pan_total: ScreenCoordinate::new(0.0, 0.0),
            pan: MomentumPart::default(),
            scalars: [MomentumPart::default(); 3],
            scalar_totals: [0.0; 3],
            replaced: false,
            elapsed: Duration::ZERO,
        };
        let mut moving = 0;
        let mut settling = 0;
        let mut motion = Duration::ZERO;
        if let Some(velocity) = options.pan_velocity {
            let speed = velocity.x.hypot(velocity.y);
            if let Some(glide) = Glide::plan(speed, &options.pan_decay) {
                momentum.pan = MomentumPart { fields: CENTER, glide, moving: true, ..Default::default() };
                moving |= CENTER;
                motion = glide.duration;
                let scale = glide.distance / speed;
                momentum.pan_total = ScreenCoordinate::new(velocity.x * scale, velocity.y * scale);
            }
        }
        let scalars = [
            (options.zoom_velocity, &options.zoom_decay, options.zoom_anchor, options.zoom_snap, ZOOM),
            (options.bearing_velocity, &options.bearing_decay, options.bearing_anchor, options.bearing_snap, BEARING),
            (options.pitch_velocity, &options.pitch_decay, options.pitch_anchor, options.pitch_snap, PITCH),
        ];
        let mut instant = true;
        for (i, (velocity, decay, anchor, snap, field)) in scalars.into_iter().enumerate() {
            let part = &mut momentum.scalars[i];
            part.fields = field | if anchor.is_some() { CENTER } else { 0 };
            if let Some(velocity) = velocity
                && let Some(glide) = Glide::plan(velocity.abs(), decay)
            {
                part.glide = glide;
                part.moving = true;
                moving |= part.fields;
                motion = motion.max(glide.duration);
                momentum.scalar_totals[i] = glide.distance.copysign(velocity);
            }
            // Without motion, a part settles only if it is near a target now.
            part.snap = snap;
            part.snap_pending = snap.is_some_and(|snap| {
                part.moving || snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING) != 0.0
            });
            if part.snap_pending {
                settling |= part.fields;
                if snap.is_some_and(|snap| snap.duration != Duration::ZERO) {
                    instant = false;
                }
            }
        }

        let start = self.now();

        // A momentum that doesn't move ends at once, without a camera change,
        // and instant snaps without motion settle at once.
        if moving == 0 && (settling == 0 || instant) {
            if settling != 0 {
                let finished = self.release_fields(settling);
                self.update_movement_flags();
                self.finish_transitions(finished);
                self.emit(TransformEvent::CameraWillChange(momentum_change(CameraChangeMode::Immediate)));
                for i in 0..momentum.scalars.len() {
                    let part = &mut momentum.scalars[i];
                    let Some(snap) = part.snap.filter(|_| part.snap_pending) else { continue };
                    part.snap_pending = false;
                    let delta = snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING);
                    self.step_scalar(i, delta, momentum.anchor(i));
                }
            }
            self.end_gesture_momentum(gesture);
            self.end_unstarted(animation, TransitionOutcome::Completed);
            if settling != 0 {
                self.emit(TransformEvent::CameraDidChange(momentum_change(CameraChangeMode::Immediate)));
            }
            return;
        }

        let fields = moving | settling;
        let transition = Transition {
            momentum: Some(momentum),
            gesture,
            command: self.reporting(),
            ..Transition::new(
                fields,
                moving,
                start,
                motion,
                animation,
                Box::new(|_, _| CameraOptions::default()),
                CameraChangeSource::Momentum,
            )
        };
        let finished = self.release_fields(fields);
        self.transitions.push(transition);
        self.update_movement_flags();
        self.finish_transitions(finished);
        self.emit(TransformEvent::CameraWillChange(momentum_change(CameraChangeMode::Animated)));
    }

    /// Runs `start` with the commands it starts attributed to `source`.
    fn with_source<R>(&mut self, source: CameraChangeSource, start: impl FnOnce(&mut Self) -> R) -> R {
        let previous = std::mem::replace(&mut self.source, source);
        let result = start(self);
        self.source = previous;
        result
    }

    /// Steps the zoom, bearing or pitch part of a momentum.
    fn step_scalar(&mut self, part: usize, amount: f64, anchor: Option<ScreenCoordinate>) -> bool {
        match part {
            MOMENTUM_ZOOM => self.step_zoom(amount, anchor),
            MOMENTUM_BEARING => {
                self.step_bearing(amount, anchor);
                true
            }
            _ => self.step_pitch(amount, anchor),
        }
    }

    /// Moves the camera as the momentum at `index` says at `now`, if it is
    /// one.
    fn advance_momentum(&mut self, index: usize, now: Option<Instant>) {
        let transition = &mut self.transitions[index];
        let Some(mut momentum) = transition.momentum.take() else { return };
        let elapsed = transition.elapsed(now);
        let (mut duration, mut moving_fields) = (transition.duration, transition.moving_fields);
        momentum.elapsed = elapsed;

        let advance = |part: &mut MomentumPart| -> f64 {
            if !part.moving {
                return 0.0;
            }
            let progress = part.glide.progress(elapsed);
            let fraction = progress - part.applied;
            part.applied = progress;
            if progress >= 1.0 {
                part.moving = false;
            }
            fraction
        };
        // A part that bounds or limits hold in place stops.
        let fraction = advance(&mut momentum.pan);
        if fraction != 0.0 {
            let total = momentum.pan_total;
            if !self.step_pan(ScreenCoordinate::new(total.x * fraction, total.y * fraction)) {
                momentum.pan.moving = false;
            }
        }
        for i in 0..momentum.scalars.len() {
            let anchor = momentum.anchor(i);
            let total = momentum.scalar_totals[i];
            let part = &mut momentum.scalars[i];
            let fraction = advance(part);
            if fraction != 0.0 && !self.step_scalar(i, total * fraction, anchor) {
                part.moving = false;
            }
            // The part settles once it stops moving, which can be before its
            // planned end when bounds, limits, or commands stopped it.
            if part.snap_pending && !part.moving {
                part.snap_pending = false;
                let snap = part.snap.unwrap_or_default();
                let delta = snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING);
                if delta != 0.0 {
                    part.snap_delta = Some(delta);
                    part.snap_start = elapsed;
                    duration = duration.max(elapsed.saturating_add(snap.duration));
                    moving_fields |= part.fields;
                }
            }
            if let Some(delta) = part.snap_delta {
                let duration = part.snap.unwrap_or_default().duration;
                // Without a clock, the snap ends with its command.
                let t = if duration.is_zero() || now.is_none() {
                    1.0
                } else {
                    mln_math::clamp_f64(elapsed.saturating_sub(part.snap_start).div_duration_f64(duration), 0.0, 1.0)
                };
                let eased = if t >= 1.0 { 1.0 } else { DEFAULT_TRANSITION_EASE.solve(t, 0.001) };
                let fraction = eased - part.snap_applied;
                part.snap_applied = eased;
                let moved = fraction == 0.0 || self.step_scalar(i, delta * fraction, anchor);
                if t >= 1.0 || !moved {
                    part.snap_delta = None;
                }
            }
        }

        // Parts that ran to their end give up their fields.
        let transition = &mut self.transitions[index];
        transition.duration = duration;
        transition.moving_fields = moving_fields;
        transition.fields = momentum.retain(transition.fields);
        transition.momentum = Some(momentum);
    }

    /// The anchor `anchor` (from the top left) as a state point, from the
    /// bottom left, with the `LatLng` under it; `None` without one. C++
    /// throws `std::domain_error` for an anchor that has no `LatLng`; the port
    /// logs it and ignores the anchor.
    fn momentum_anchor(&self, anchor: Option<ScreenCoordinate>) -> Option<(ScreenCoordinate, LatLng)> {
        let anchor = anchor?;
        let point = ScreenCoordinate::new(anchor.x, f64::from(self.state.get_size().height) - anchor.y);
        match self.state.screen_coordinate_to_lat_lng(&point, WrapMode::Unwrapped) {
            Ok(lat_lng) => Some((point, lat_lng)),
            Err(e) => {
                Log::error(Event::General, &e.message);
                None
            }
        }
    }

    /// Moves the center so that `lat_lng` is at `point` again, keeping the
    /// altitude in meters, which moving the center keeps in pixels.
    fn hold_momentum_anchor(&mut self, anchor: Option<(ScreenCoordinate, LatLng)>) {
        let Some((point, lat_lng)) = anchor else { return };
        let altitude = self.state.get_center_altitude();
        if let Err(e) = self.state.move_lat_lng(&lat_lng, &point) {
            Log::error(Event::General, &e.message);
        }
        self.state.set_center_altitude(altitude);
    }

    // Momentum steps, applied to the state as it stands. Each returns whether
    // it moved the camera, which bounds and limits can prevent.

    fn step_pan(&mut self, offset: ScreenCoordinate) -> bool {
        // Each step moves the content no farther than a drag moves it in one
        // event, so the travel on screen stays even at high pitch. A frame
        // that would need more steps than a frame can afford takes longer
        // ones.
        const MAX_STEP: f64 = 16.0;
        const MAX_STEPS: f64 = 100.0;
        let distance = offset.x.hypot(offset.y);
        if distance.is_nan() || distance <= 0.0 {
            return true;
        }
        let before = self.get_lat_lng(WrapMode::Unwrapped);
        let altitude = self.state.get_center_altitude();
        let steps = f64::min((distance / MAX_STEP).ceil(), MAX_STEPS);
        let step = ScreenCoordinate::new(offset.x / steps, offset.y / steps);
        let bounded = self.state.get_lat_lng_bounds() != LatLngBounds::default();
        for _ in 0..steps as u32 {
            if self.globe_on_screen() {
                self.step_globe_pan(&step);
                continue;
            }
            let size = self.state.get_size();
            let center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
            let point = ScreenCoordinate::new(center.x - step.x, center.y - step.y);
            // C++ throws std::domain_error for a step that has no LatLng; the
            // port logs it and stops the step.
            let unwrapped = match self.screen_coordinate_to_lat_lng(&point, WrapMode::Unwrapped) {
                Ok(lat_lng) => lat_lng,
                Err(e) => {
                    Log::error(Event::General, &e.message);
                    break;
                }
            };
            let mut camera = CameraOptions {
                center: Some(if bounded { unwrapped } else { unwrapped.wrapped() }),
                ..Default::default()
            };
            let mut zoom = self.state.get_zoom();
            self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
            self.state.set_lat_lng_zoom(&camera.center.unwrap_or(unwrapped), zoom);
        }
        self.state.set_center_altitude(altitude);
        self.get_lat_lng(WrapMode::Unwrapped) != before
    }

    /// One pan step on the globe, as a drag around the view center
    /// ([`Self::move_by_with_anchor`] without an anchor) makes it: the
    /// planet turns, the bearing too when it is free, and the zoom keeps the
    /// planet's size as the latitude changes.
    fn step_globe_pan(&mut self, step: &ScreenCoordinate) {
        let size = self.state.get_size();
        let view_center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
        let grab = ScreenCoordinate::new(view_center.x, f64::from(size.height) - view_center.y);
        let pan_delta = ScreenCoordinate::new(step.x, -step.y);
        let (center, bearing) = if self.globe_free_bearing {
            let drag = VerticalPerspectiveProjection::drag_camera(&self.state, &grab, &pan_delta);
            (drag.center, Some(drag.bearing))
        } else {
            (VerticalPerspectiveProjection::drag_center(&self.state, &grab, &pan_delta), None)
        };
        let center = self.state.constrained_center(&center, self.get_zoom());
        let zoom = self.get_zoom()
            + VerticalPerspectiveProjection::zoom_adjustment(
                self.get_lat_lng(WrapMode::Wrapped).latitude(),
                center.latitude(),
            );
        if let Some(bearing) = bearing {
            self.state.set_bearing(mln_math::deg2rad(-bearing));
        }
        self.state.set_lat_lng_zoom(&center, zoom);
    }

    fn step_zoom(&mut self, zoom: f64, anchor: Option<ScreenCoordinate>) -> bool {
        let before = self.state.get_zoom();
        let altitude = self.state.get_center_altitude();
        let anchor = self.momentum_anchor(anchor);
        let center = self.get_lat_lng(WrapMode::Unwrapped);
        let mut target = mln_math::clamp_f64(
            before + zoom,
            self.state.get_min_zoom_at_latitude(center.latitude()),
            self.state.get_max_zoom(),
        );
        let mut camera = CameraOptions { center: Some(center), ..Default::default() };
        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut target);
        self.state.set_lat_lng_zoom(&camera.center.unwrap_or(center), target);
        // The altitude in meters holds before the anchor correction, which
        // reads the projection, and through the correction's change of
        // center.
        self.state.set_center_altitude(altitude);
        match anchor {
            // On the globe the zoom around the anchor is the globe's, as in
            // apply_transitions.
            Some((point, lat_lng)) if self.globe_on_screen() && self.state.get_zoom() != before => {
                let zoom_delta = self.state.get_zoom() - before;
                VerticalPerspectiveProjection::zoom_around_point(
                    &mut self.state,
                    &point,
                    &lat_lng,
                    zoom_delta,
                    self.globe_free_bearing,
                );
            }
            _ => self.hold_momentum_anchor(anchor),
        }
        self.state.get_zoom() != before
    }

    fn step_bearing(&mut self, bearing: f64, anchor: Option<ScreenCoordinate>) {
        let anchor = self.momentum_anchor(anchor);
        self.state.set_bearing(mln_math::wrap(self.state.get_bearing() - mln_math::deg2rad(bearing), -PI, PI));
        self.hold_momentum_anchor(anchor);
    }

    fn step_pitch(&mut self, pitch: f64, anchor: Option<ScreenCoordinate>) -> bool {
        let anchor = self.momentum_anchor(anchor);
        let before = self.state.get_pitch();
        let max_pitch = get_max_pitch_for_edge_insets(&self.state, &self.state.get_edge_insets());
        self.state.set_pitch(mln_math::clamp_f64(
            before + mln_math::deg2rad(pitch),
            self.state.get_min_pitch(),
            max_pitch,
        ));
        if self.state.get_pitch() == before {
            return false;
        }
        self.hold_momentum_anchor(anchor);
        true
    }

    /// Puts the camera's animations on the host's frame clock: commands start
    /// at the latest frame's time rather than at `Instant::now()` when they are
    /// made, and the map samples them at it. Each frame then shows its
    /// animations exactly one frame further on, whenever the input or the
    /// map's update ran, and an animation started between frames moves by
    /// that frame's interval on the next one: no frame repeats the
    /// camera, and none skips ahead. `None` goes back to `Instant::now()`.
    ///
    /// Orbis starts animations on the first frame after the call, which
    /// keeps the camera still for that frame; a glide that continues a drag
    /// would pause there.
    pub fn set_frame_time(&mut self, time: Option<Instant>) {
        self.frame_time.set(time);
    }

    /// The clock that [`set_frame_time`](Self::set_frame_time) sets.
    pub(crate) fn frame_clock(&self) -> FrameClock {
        self.frame_time.clone()
    }

    /// The host's frame time, unless it is stale: older than
    /// [`STALE_FRAME_TIME`], as when the host stopped drawing frames or
    /// forgot to set it this frame. A stale frame time would start a command
    /// in the past, which the next frame would show already under way or
    /// over.
    pub(crate) fn frame_time(&self) -> Option<Instant> {
        self.fresh_frame_time(Instant::now())
    }

    fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
        self.frame_time.get().filter(|&time| now.saturating_duration_since(time) <= STALE_FRAME_TIME)
    }

    /// When commands start: the frame time, or now.
    fn now(&self) -> Instant {
        let now = Instant::now();
        self.fresh_frame_time(now).unwrap_or(now)
    }

    pub(crate) fn cancel_transitions(&mut self) {
        let mut finished = std::mem::take(&mut self.transitions);
        for transition in &mut finished {
            transition.ended_by(TransitionOutcome::Cancelled);
        }
        self.update_movement_flags();
        self.finish_transitions(finished);
    }

    /// Cancels the commands whose [`AnimationOptions::transition_id`] equals
    /// `transition_id`, leaves the others running, and returns whether any
    /// command ended.
    pub fn cancel_transitions_with_id(&mut self, transition_id: u64) -> bool {
        let mut finished: Vec<_> = self
            .transitions
            .extract_if(.., |transition| transition.animation.transition_id == Some(transition_id))
            .collect();
        if finished.is_empty() {
            return false;
        }
        for transition in &mut finished {
            transition.ended_by(TransitionOutcome::Cancelled);
        }
        self.update_movement_flags();
        self.finish_transitions(finished);
        true
    }

    /// Ends the running commands as closed, without a camera change. A map's
    /// owner calls it before it drops the map, so that it hears every
    /// command's end.
    pub fn close(&mut self) {
        for transition in std::mem::take(&mut self.transitions) {
            let end = TransitionEnd { outcome: TransitionOutcome::Closed, ..transition.end() };
            self.report_end(transition.command, transition.animation.transition_id, end);
        }
        self.update_movement_flags();
    }

    // MARK: - Gesture

    /// Moves the camera relative to where it is, as a gesture does
    /// (the C API's `mln_map_apply_camera_delta`). See
    /// [`CameraDelta`].
    pub fn apply_camera_delta(&mut self, delta: &CameraDelta) -> Result<CameraCommandId, CameraError> {
        delta.validate()?;
        Ok(self.command(|transform| transform.apply_camera_delta_now(delta)))
    }

    fn apply_camera_delta_now(&mut self, delta: &CameraDelta) {
        let source = gesture_source(delta.phase);
        let pans = delta.offset.is_some();
        let eases = delta.scale.is_some() || delta.bearing.is_some() || delta.pitch.is_some();
        // With momentum, the command's end is the momentum's, and the delta's
        // own changes, which can't animate, apply before it starts.
        // Otherwise the pan and the ease end the command together.
        let parts = match delta.momentum {
            Some(_) => AnimationOptions::default(),
            None => delta.animation,
        };
        self.silent = delta.momentum.is_some();
        self.join_ends(u32::from(pans) + u32::from(eases));
        self.gesture_phase_before(delta.phase);
        if delta.phase != GesturePhase::None {
            self.gesture.change(
                delta.scale.is_some_and(|scale| scale != 1.0),
                delta.bearing.is_some_and(|bearing| bearing != 0.0),
                delta.pitch.is_some_and(|pitch| pitch != 0.0),
            );
        }
        self.with_source(source, |transform| {
            if let Some(offset) = delta.offset {
                // Validation keeps the offset finite, so it has a LatLng. The
                // anchor is the point the drag holds, which the globe keeps
                // under it.
                let _ = transform.move_by_with_anchor(&offset, delta.anchor, &parts);
            }
            if eases {
                let current = transform.get_camera_options(None);
                let target = CameraOptions {
                    zoom: delta.scale.map(|scale| current.zoom.unwrap_or(0.0) + scale.log2()),
                    bearing: delta.bearing.map(|bearing| current.bearing.unwrap_or(0.0) + bearing),
                    pitch: delta.pitch.map(|pitch| current.pitch.unwrap_or(0.0) + pitch),
                    anchor: delta.anchor,
                    ..CameraOptions::default()
                };
                transform.ease_to(&target, &parts);
            }
        });
        self.silent = false;
        match delta.momentum {
            Some(mut momentum) => {
                self.gesture.mask_snaps(&mut momentum);
                // The gesture ends as its momentum starts, rather than in
                // `gesture_phase_after`, so that a momentum with nothing to
                // move, which ends at once, ends it too.
                self.gesture.active = false;
                let serial = self.gesture.serial;
                self.with_source(CameraChangeSource::Momentum, |transform| {
                    transform.start_momentum_now(&momentum, &delta.animation, Some(serial));
                });
            }
            None if !pans && !eases => self.end_unstarted(&delta.animation, TransitionOutcome::Completed),
            None => {}
        }
        self.gesture_phase_after(delta.phase, delta.momentum.is_some());
    }

    /// Moves the camera to absolute values, as a command or a gesture
    /// (the C API's `mln_map_update_camera`). See [`CameraUpdate`].
    pub fn update_camera(&mut self, update: &CameraUpdate) -> CameraCommandId {
        self.command(|transform| transform.update_camera_now(update))
    }

    fn update_camera_now(&mut self, update: &CameraUpdate) {
        self.gesture_phase_before(update.phase);
        if update.phase != GesturePhase::None {
            // A gesture's update can repeat a field it doesn't change.
            let current = self.get_camera_options(None);
            let changes = |value: Option<f64>, now: Option<f64>| value.is_some() && value != now;
            self.gesture.change(
                changes(update.camera.zoom, current.zoom),
                changes(update.camera.bearing, current.bearing),
                changes(update.camera.pitch, current.pitch),
            );
        }
        self.with_source(gesture_source(update.phase), |transform| match update.mode {
            CameraUpdateMode::Jump => {
                transform.ease(&update.camera, &AnimationOptions { duration: None, ..update.animation });
            }
            CameraUpdateMode::Ease => transform.ease(&update.camera, &update.animation),
            CameraUpdateMode::Fly => transform.fly(&update.camera, &update.animation, false),
        });
        self.gesture_phase_after(update.phase, false);
    }

    /// `Begin` cancels the running commands, and `Begin` and `Update` mark
    /// the gesture, before its change applies, so that the change follows
    /// the gesture rules (an ease doesn't fly, and wraps the longitude as a
    /// drag). The first phase after a gesture ended starts a new one, which
    /// an earlier gesture's momentum no longer ends.
    fn gesture_phase_before(&mut self, phase: GesturePhase) {
        if phase != GesturePhase::None && (phase == GesturePhase::Begin || !self.gesture.active) {
            self.gesture = GestureState { serial: self.gesture.serial.wrapping_add(1), ..GestureState::default() };
        }
        if phase == GesturePhase::Begin {
            self.cancel_transitions();
        }
        if matches!(phase, GesturePhase::Begin | GesturePhase::Update) {
            self.gesture.active = true;
            self.set_gesture_in_progress(true);
        }
    }

    /// `Cancel` cancels the running commands after its change applies, and
    /// `End` and `Cancel` end the gesture: at once, or when its momentum
    /// ends.
    fn gesture_phase_after(&mut self, phase: GesturePhase, momentum: bool) {
        if phase == GesturePhase::Cancel {
            self.cancel_transitions();
        }
        if matches!(phase, GesturePhase::End | GesturePhase::Cancel) {
            self.gesture.active = false;
            if !momentum {
                self.set_gesture_in_progress(false);
            }
        }
    }

    /// The end of a gesture's momentum ends the gesture, unless another
    /// gesture started since.
    fn end_gesture_momentum(&mut self, gesture: Option<u64>) {
        if gesture == Some(self.gesture.serial) && !self.gesture.active {
            self.set_gesture_in_progress(false);
        }
    }

    pub(crate) fn set_gesture_in_progress(&mut self, in_progress: bool) {
        self.state.set_gesture_in_progress(in_progress);
    }

    pub fn is_gesture_in_progress(&self) -> bool {
        self.state.is_gesture_in_progress()
    }

    // MARK: - Transform state

    pub fn get_state(&self) -> &TransformState {
        &self.state
    }

    #[cfg(test)]
    pub(crate) fn is_rotating(&self) -> bool {
        self.state.is_rotating()
    }

    #[cfg(test)]
    pub(crate) fn is_scaling(&self) -> bool {
        self.state.is_scaling()
    }

    #[cfg(test)]
    pub(crate) fn is_panning(&self) -> bool {
        self.state.is_panning()
    }

    // MARK: Conversion and projection

    pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
        let mut point = self.state.lat_lng_to_screen_coordinate(lat_lng);
        point.y = f64::from(self.state.get_size().height) - point.y;
        point
    }

    /// The location under `point`, in screen coordinates (y down).
    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN
    /// or infinite point.
    pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
        let mut flipped_point = *point;
        flipped_point.y = f64::from(self.state.get_size().height) - flipped_point.y;
        self.state.screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
    }

    #[cfg(test)]
    pub(crate) fn get_free_camera_options(&self) -> FreeCameraOptions {
        self.state.get_free_camera_options()
    }

    pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
        self.cancel_transitions();
        self.state.set_free_camera_options(options);
    }
}

fn gesture_source(phase: GesturePhase) -> CameraChangeSource {
    if phase == GesturePhase::None { CameraChangeSource::Command } else { CameraChangeSource::Gesture }
}

/// An animation frame's padding, `t` of the way from `start` to `end`; `None`
/// when it has none (see [`frame_edge_insets`]). C++ interpolates the insets
/// even when they don't change; the port keeps them, so that infinite insets
/// don't log on every frame.
fn interpolate_edge_insets(start: &EdgeInsets, end: &EdgeInsets, t: f64) -> Option<EdgeInsets> {
    if start == end {
        return Some(*end);
    }
    frame_edge_insets(
        interpolate(&start.top, &end.top, t),
        interpolate(&start.left, &end.left, t),
        interpolate(&start.bottom, &end.bottom, t),
        interpolate(&start.right, &end.right, t),
    )
}

/// We don't want to show horizon: limit max pitch based on edge insets.
/// (`Transform::getMaxPitchForEdgeInsets`, called on the state inside the
/// frame function.)
fn get_max_pitch_for_edge_insets(state: &TransformState, insets: &EdgeInsets) -> f64 {
    // See TransformState::getCenterOffset.
    let center_offset_y = 0.5 * (insets.top - insets.bottom);
    if center_offset_y == 0.0 {
        return state.get_max_pitch();
    }

    let height = state.get_size().height;
    debug_assert!(height != 0);
    let field_of_view = f64::from(state.get_field_of_view());
    // Half of fov is the field of view above perspective center.
    let tangent_of_fov_above_center_angle =
        (0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
    let fov_above_center = tangent_of_fov_above_center_angle.atan();
    f64::max(state.get_min_pitch(), state.get_max_pitch() + field_of_view / 2.0 - fov_above_center)
}

#[cfg(test)]
#[path = "transform_test.rs"]
mod transform_test;