rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
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
// ---------------------------------------------------------------------------
//! # Map state -- the central per-frame state object
//!
//! [`MapState`] owns every piece of data the engine needs todescribe a
//! single frame of the map: camera, layers, terrain, animation, and
//! precomputed derived values (zoom level, viewport bounds, frustum).
//!
//! ## Lifecycle (host <-> engine <-> renderer)
//!
//! ```text
//!  Host application                    Engine (MapState)           Renderer
//!  +----------------+                  +--------------+           +----------+
//!  | winit / Bevy   |-- handle_input ->|              |           |          |
//!  | event loop     |-- fly_to ------->|  update()    |           |          |
//!  |                |                  |  update_     |           |          |
//!  |                |                  |  with_dt()   |           |          |
//!  |                |                  |              |           |          |
//!  |                |                  | frame_output +---------->| render() |
//!  +----------------+                  +--------------+           +----------+
//! ```
//!
//! 1. **Input** -- the host feeds [`InputEvent`]s via
//!    [`handle_input`](MapState::handle_input).
//! 2. **Update** -- the host calls [`update`](MapState::update) (or
//!    [`update_with_dt`](MapState::update_with_dt)) once per frame.
//!    This ticks the camera animator, recomputes the zoom level and
//!    viewport bounds, rebuilds terrain meshes, and iterates the layer
//!    stack to update tile, vector, and model data.
//! 3. **Read** -- the renderer reads derived state either through direct
//!    field access (`camera`, `vector_meshes`, `model_instances`) or
//!    through accessor methods (`visible_tiles()`, `terrain_meshes()`,
//!    `zoom_level()`).  Alternatively, call
//!    [`frame_output`](MapState::frame_output) to obtain a detached
//!    snapshot that can be sent to a render thread.
//! - **Derived state**:
//!    - `zoom_level` -- Current integer zoom level (0-22).
//!    - `viewport_bounds` -- Viewport bounding box in Web Mercator world space.
//!    - `scene_viewport_bounds` -- Viewport bounding box in the active planar scene projection.
//!    - `frustum` -- View frustum planes (derived from the camera VP matrix).
//!    - `terrain_meshes` -- Terrain meshes produced during this frame's `update()`.
//!    - `hillshade_rasters` -- Prepared hillshade rasters for the last `update()`.
//!    - `visible_tiles` -- Visible tiles produced by the tile layer (or set externally).
//! - **Per-frame layer output**:
//!    - `vector_meshes` -- Tessellated vector meshes from the last `update()`.
//!    - `model_instances` -- 3D model instances collected from all visible
//!      [`ModelLayer`](crate::layers::ModelLayer)s during the last `update()`.
//!    - `placed_symbols` -- Placed symbols after collision resolution.
//!
//! ## Thread safety
//!
//! `MapState` is `Send + Sync`.  The facade crate's [`MapHandle`]
//! wraps it in an `RwLock`, giving shared read access for renderers
//! and exclusive write access for the input / update path.
//!
//! ## Coordinate conventions
//!
//! All world-space positions are in **Web Mercator meters**, and the
//! camera uses a **camera-relative** origin to avoid f32 jitter at
//! large coordinates.  See the [`camera`](crate::camera) module docs
//! for the full coordinate-system description.
//!
//! [`MapHandle`]: https://docs.rs/rustial/latest/rustial/struct.MapHandle.html
// ---------------------------------------------------------------------------

use crate::async_data::{
    AsyncDataPipeline, DataTaskPool, TerrainTaskInput, VectorCacheKey, VectorTaskInput,
};
use crate::camera::{Camera, CameraConstraints, CameraController, CameraMode};
use crate::camera_animator::CameraAnimator;
use crate::camera_projection::CameraProjection;
use crate::geo_wrap::wrap_lon_180;
use crate::geometry::{FeatureCollection, PropertyValue};
use crate::input::InputEvent;
use crate::layer::Layer;
use crate::layer::LayerId;
use crate::layers::{FeatureProvenance, LayerStack, VectorMeshData, VectorStyle};
use crate::loading_placeholder::{LoadingPlaceholder, PlaceholderGenerator, PlaceholderStyle};
use crate::models::ModelInstance;
use crate::picking::{HitCategory, HitProvenance, PickHit, PickOptions, PickQuery, PickResult};
use crate::query::{
    feature_id_for_feature, geometry_hit_distance, FeatureState, FeatureStateId, QueriedFeature,
    QueryOptions,
};
use crate::streamed_payload::{
    collect_affected_symbol_payloads, prune_affected_symbol_payloads,
    resolve_streamed_vector_layer_refresh, symbol_query_payloads_from_optional,
    StreamedPayloadView, StreamedSymbolPayloadKey, StreamedVectorLayerRefreshSpec,
    SymbolDependencyPayload, SymbolQueryPayload, TileQueryPayload, VisiblePlacedSymbolView,
};
use crate::style::{MapStyle, StyleDocument, StyleError};
use crate::symbols::{PlacedSymbol, SymbolAssetRegistry, SymbolPlacementEngine};
use crate::terrain::{PreparedHillshadeRaster, TerrainConfig, TerrainManager, TerrainMeshData};
use crate::tile_cache::TileCacheStats;
use crate::tile_lifecycle::TileLifecycleDiagnostics;
use crate::tile_manager::{TileManagerCounters, TileSelectionStats};
use crate::tile_manager::{VisibleTile, ZoomPrefetchDirection};
use crate::tile_request_coordinator::{
    CoordinatorConfig, CoordinatorStats, SourcePriority, TileRequestCoordinator,
};
use crate::tile_source::TileSourceDiagnostics;
use rustial_math::{
    visible_tiles, visible_tiles_flat_view_with_config, FlatTileSelectionConfig, Frustum,
    GeoBounds, GeoCoord, TileId, WebMercator, WorldBounds, WorldCoord, MAX_ZOOM,
};
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;

mod async_pipeline;
mod heavy_layers;
mod picking;
#[cfg(test)]
mod tests;
mod tile_selection;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Earth's equatorial circumference in meters (2*pi * WGS-84 semi-major axis).
///
/// Used to convert between camera `meters_per_pixel` and slippy-map zoom
/// levels.  Matches the constant embedded in [`WebMercator::world_size()`].
const WGS84_CIRCUMFERENCE: f64 = 2.0 * std::f64::consts::PI * 6_378_137.0;

/// Standard raster tile edge length in pixels (universal slippy-map
/// convention).
const TILE_PX: f64 = 256.0;

/// Fraction of a source budget that may be spent on speculative prefetch.
const SPECULATIVE_PREFETCH_BUDGET_FRACTION: f64 = 0.25;

/// Fallback speculative request cap when global coordination is disabled.
const DEFAULT_SPECULATIVE_PREFETCH_REQUEST_BUDGET: usize = 8;

/// Minimum fractional zoom change treated as intentional zoom motion.
const ZOOM_DIRECTION_PREFETCH_THRESHOLD: f64 = 0.01;

fn viewport_sample_points(width: f64, height: f64) -> Vec<(f64, f64)> {
    const FRACTIONS: [f64; 7] = [0.0, 1.0 / 6.0, 2.0 / 6.0, 0.5, 4.0 / 6.0, 5.0 / 6.0, 1.0];
    let mut samples = Vec::with_capacity(FRACTIONS.len() * FRACTIONS.len());
    for fy in FRACTIONS {
        for fx in FRACTIONS {
            samples.push((width * fx, height * fy));
        }
    }
    samples
}

fn perspective_viewport_overscan(pitch: f64) -> f64 {
    let normalized_pitch = (pitch / std::f64::consts::FRAC_PI_2).clamp(0.0, 1.0);
    1.3 + 0.5 * normalized_pitch
}

fn terrain_base_tile_budget(required_tiles: usize) -> usize {
    required_tiles.clamp(80, 256)
}

fn terrain_horizon_tile_budget(base_budget: usize, pitch: f64) -> usize {
    if pitch <= 0.5 {
        0
    } else {
        (base_budget / 3).clamp(24, 96)
    }
}

// ---------------------------------------------------------------------------
// FitBoundsOptions
// ---------------------------------------------------------------------------

/// Padding in logical pixels for [`MapState::fit_bounds`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FitBoundsPadding {
    /// Top padding in logical pixels.
    pub top: f64,
    /// Bottom padding in logical pixels.
    pub bottom: f64,
    /// Left padding in logical pixels.
    pub left: f64,
    /// Right padding in logical pixels.
    pub right: f64,
}

impl Default for FitBoundsPadding {
    fn default() -> Self {
        Self {
            top: 0.0,
            bottom: 0.0,
            left: 0.0,
            right: 0.0,
        }
    }
}

impl FitBoundsPadding {
    /// Uniform padding on all sides.
    pub fn uniform(px: f64) -> Self {
        Self {
            top: px,
            bottom: px,
            left: px,
            right: px,
        }
    }
}

/// Options for [`MapState::fit_bounds`].
///
/// Mirrors MapLibre's `fitBounds` options.
#[derive(Debug, Clone)]
pub struct FitBoundsOptions {
    /// Padding in logical pixels.
    pub padding: FitBoundsPadding,
    /// Maximum zoom level to use. `None` = no cap.
    pub max_zoom: Option<f64>,
    /// Whether to animate the transition (fly-to). Default: `true`.
    pub animate: bool,
    /// Explicit animation duration in seconds. Only used when `animate` is `true`.
    pub duration: Option<f64>,
    /// Target bearing (yaw) in radians. `None` = keep current.
    pub bearing: Option<f64>,
    /// Target pitch in radians. `None` = keep current.
    pub pitch: Option<f64>,
}

impl Default for FitBoundsOptions {
    fn default() -> Self {
        Self {
            padding: FitBoundsPadding::default(),
            max_zoom: None,
            animate: true,
            duration: None,
            bearing: None,
            pitch: None,
        }
    }
}

// ---------------------------------------------------------------------------
// Sync-path vector tessellation cache
// ---------------------------------------------------------------------------

/// Cache key for the sync-path per-layer vector tessellation cache.
///
/// When no async pipeline is active, `update_heavy_layers` uses this cache
/// to skip re-tessellation when neither the style, the feature data, nor the
/// projection have changed since the last frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct SyncVectorCacheKey {
    /// Stable layer identity.
    layer_id: LayerId,
    /// Style fingerprint from [`VectorStyle::tessellation_fingerprint`].
    style_fingerprint: u64,
    /// Feature data generation counter.
    data_generation: u64,
    /// Projection at tessellation time.
    projection: CameraProjection,
}

/// Cached tessellation result for a single vector layer in the sync path.
#[derive(Clone)]
struct SyncVectorCacheEntry {
    mesh: VectorMeshData,
}

// ---------------------------------------------------------------------------
// FrameOutput
// ---------------------------------------------------------------------------

/// Bundled per-frame snapshot produced by [`MapState::update`] for renderers.
///
/// Contains **everything** a renderer needs to draw a single frame,
/// avoiding the need to reach into `MapState` internals.  All data is
/// owned (`Clone`d from `MapState`), so the struct can be sent to a
/// render thread without holding a lock.
///
/// # Usage
///
/// ```rust,ignore
/// state.update();
/// let frame = state.frame_output();
/// // Send `frame` to the GPU thread ...
/// ```
#[derive(Debug, Default)]
pub struct FrameOutput {
    /// View-projection matrix (f64 precision, camera-relative origin).
    ///
    /// Cast to `glam::Mat4` (f32) when uploading to a GPU uniform buffer.
    /// The f64 source preserves precision for CPU-side picking and culling.
    pub view_projection: glam::DMat4,

    /// View frustum planes for CPU-side culling.
    ///
    /// `None` only before the first call to `update()`.
    pub frustum: Option<Frustum>,

    /// Visible tiles (loaded imagery or parent-tile fallbacks).
    ///
    /// Wrapped in `Arc` for zero-copy sharing with render threads.
    pub tiles: Arc<Vec<VisibleTile>>,

    /// Terrain meshes to render (one per visible tile with elevation data).
    ///
    /// Wrapped in `Arc` for zero-copy sharing with render threads.
    pub terrain: Arc<Vec<TerrainMeshData>>,

    /// Prepared DEM-derived hillshade rasters aligned to the visible terrain set.
    pub hillshade: Arc<Vec<PreparedHillshadeRaster>>,

    /// Tessellated vector meshes (polygons, lines, points).
    ///
    /// Wrapped in `Arc` for zero-copy sharing with render threads.
    pub vectors: Arc<Vec<VectorMeshData>>,

    /// Placed 3D model instances to render.
    ///
    /// Wrapped in `Arc` for zero-copy sharing with render threads.
    pub models: Arc<Vec<ModelInstance>>,

    /// Placed symbol instances after collision resolution.
    pub symbols: Arc<Vec<PlacedSymbol>>,

    /// Visualization overlay data (grids, columns, etc.) from the last update.
    pub visualization: Arc<Vec<crate::visualization::VisualizationOverlay>>,

    /// Loading placeholders for visible tiles that have no data yet.
    ///
    /// Renderers should draw styled rectangles at these world bounds
    /// before or behind the opaque tile pass so that loading areas
    /// never appear as blank gaps.
    pub placeholders: Arc<Vec<LoadingPlaceholder>>,

    /// Georeferenced image overlays (image/video/canvas sources).
    ///
    /// Each entry is a textured quad defined by four world-space corners
    /// plus RGBA8 pixel data.  Renderers should draw these between the
    /// tile and vector passes.
    pub image_overlays: Arc<Vec<crate::layers::ImageOverlayData>>,

    /// Current integer zoom level (0-22).
    pub zoom_level: u8,
}

/// Snapshot of the active tile-layer pipeline for debug/telemetry use.
#[derive(Debug, Clone, Default)]
pub struct TilePipelineDiagnostics {
    /// Name of the tile layer providing the snapshot.
    pub layer_name: String,
    /// Number of visible tiles in the layer's last visible set.
    pub visible_tiles: usize,
    /// Number of visible tiles with exact or fallback data loaded.
    pub visible_loaded_tiles: usize,
    /// Number of visible tiles currently using fallback imagery.
    pub visible_fallback_tiles: usize,
    /// Number of visible tiles with no imagery currently available.
    pub visible_missing_tiles: usize,
    /// Number of visible tiles rendered as overzoomed.
    pub visible_overzoomed_tiles: usize,
    /// Per-frame tile-selection stats from the last update.
    pub selection_stats: TileSelectionStats,
    /// Cumulative tile-manager counters.
    pub counters: TileManagerCounters,
    /// Current cache state counts.
    pub cache_stats: TileCacheStats,
    /// Optional source transport diagnostics.
    pub source_diagnostics: Option<TileSourceDiagnostics>,
}

/// Configuration for camera-motion sampling and look-ahead prediction.
#[derive(Debug, Clone, PartialEq)]
pub struct CameraVelocityConfig {
    /// Number of recent motion samples to retain.
    ///
    /// The effective velocity is computed from the oldest and newest retained
    /// samples, so larger windows smooth short spikes while smaller windows
    /// react more quickly to abrupt changes.
    pub sample_window: usize,
    /// Look-ahead time in seconds used to project the current pan motion.
    pub look_ahead_seconds: f64,
}

impl Default for CameraVelocityConfig {
    fn default() -> Self {
        Self {
            sample_window: 6,
            look_ahead_seconds: 0.5,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct CameraMotionSample {
    time_seconds: f64,
    target_world: glam::DVec2,
}

/// Smoothed camera pan state derived from recent update frames.
#[derive(Debug, Clone, PartialEq)]
pub struct CameraMotionState {
    /// Smoothed pan velocity in Web Mercator meters per second.
    pub pan_velocity_world: glam::DVec2,
    /// Predicted camera target in Web Mercator meters after the configured
    /// look-ahead interval.
    pub predicted_target_world: glam::DVec2,
    /// Predicted viewport bounds translated by the same look-ahead motion.
    pub predicted_viewport_bounds: WorldBounds,
}

impl Default for CameraMotionState {
    fn default() -> Self {
        let zero = WorldCoord::new(0.0, 0.0, 0.0);
        Self {
            pan_velocity_world: glam::DVec2::ZERO,
            predicted_target_world: glam::DVec2::ZERO,
            predicted_viewport_bounds: WorldBounds::new(zero, zero),
        }
    }
}

// ---------------------------------------------------------------------------
// MapState
// ---------------------------------------------------------------------------

/// The central state object consumed by renderers each frame.
///
/// Owns the camera, layer stack, terrain manager, camera animator,
/// and all per-frame derived data (zoom level, viewport bounds,
/// frustum, mesh caches).
///
/// # Field visibility
///
/// All fields are private.  Use accessor methods for reads and
/// targeted setters for writes:
///
/// | Need | Method |
/// |------|--------|
/// | Read camera | [`camera()`](Self::camera) |
/// | Set viewport size | [`set_viewport`](Self::set_viewport) |
/// | Set camera target | [`set_camera_target`](Self::set_camera_target) |
/// | Set camera distance | [`set_camera_distance`](Self::set_camera_distance) |
/// | Set camera pitch/yaw | [`set_camera_pitch`](Self::set_camera_pitch), [`set_camera_yaw`](Self::set_camera_yaw) |
/// | Toggle projection | [`set_camera_mode`](Self::set_camera_mode) |
/// | Set camera FOV | [`set_camera_fov_y`](Self::set_camera_fov_y) |
/// | Read constraints | [`constraints()`](Self::constraints) |
/// | Set max pitch | [`set_max_pitch`](Self::set_max_pitch) |
/// | Add a layer | [`push_layer`](Self::push_layer) |
/// | Read layers | [`layers()`](Self::layers) |
/// | Read vector meshes | [`vector_meshes()`](Self::vector_meshes) |
/// | Read model instances | [`model_instances()`](Self::model_instances) |
/// | Dispatch input | [`handle_input`](Self::handle_input) |
/// | Animate camera | [`fly_to`](Self::fly_to) |
/// | Check animator | [`animator()`](Self::animator) |
/// | Replace terrain | [`set_terrain`](Self::set_terrain) |
/// | Read terrain state | [`terrain()`](Self::terrain) |
pub struct MapState {
    // -- Inputs -----------------------------------------------------------
    /// Camera controlling the view (target, orbit params, projection).
    camera: Camera,

    /// Per-frame clamps applied to the camera by [`CameraController`](crate::CameraController).
    constraints: CameraConstraints,

    /// Ordered layer stack (rendered bottom-to-top).
    pub(crate) layers: LayerStack,

    /// Optional style/runtime document that produced the current layer stack.
    style: Option<MapStyle>,

    /// Terrain elevation manager.
    pub(crate) terrain: TerrainManager,

    /// Camera animator for smooth zoom, rotation, and pan momentum.
    animator: CameraAnimator,

    // -- Animation-aware data update throttle ------------------------------
    /// Minimum interval (seconds) between heavy layer updates (terrain
    /// meshing, vector tessellation, symbol placement, model collection)
    /// while a coordinated camera animation (fly-to / ease-to) is active.
    ///
    /// Tile layer updates (HTTP response polling, visible tile selection,
    /// and tile request issuing) always run every frame regardless of this
    /// interval, since they are lightweight and essential for keeping the
    /// visible tile set in sync with the camera.
    ///
    /// Default: `0.15` (~6-7 heavy data updates per second during animation).
    /// Set to `0.0` to disable throttling (matches the MapLibre model of
    /// updating every frame, but may cause stutter with heavy layers).
    ///
    /// **Note:** When an async task pool is active (see
    /// [`set_task_pool`](Self::set_task_pool)), this interval is ignored
    /// because dispatch + poll is cheap regardless of animation state.
    data_update_interval: f64,

    /// Accumulated time since the last full data update during animation.
    data_update_elapsed: f64,

    // -- Async retained data pipeline ------------------------------------
    /// Optional async data pipeline for offloading heavy CPU work.
    ///
    /// When set, `update_with_dt` dispatches terrain/vector/symbol work
    /// to background tasks and polls completed results each frame, matching
    /// the MapLibre/Mapbox web worker model.
    ///
    /// When `None`, the engine falls back to synchronous inline execution.
    async_pipeline: Option<AsyncDataPipeline>,

    // -- Per-frame derived state (private, recomputed by update) -----------
    /// Current integer zoom level (derived from `camera.meters_per_pixel()`).
    zoom_level: u8,

    /// Viewport bounding box in Web Mercator world space.
    viewport_bounds: WorldBounds,

    /// Viewport bounding box in the active planar scene projection.
    scene_viewport_bounds: WorldBounds,

    /// View frustum planes (derived from the camera VP matrix).
    frustum: Option<Frustum>,

    /// Terrain meshes produced during this frame's `update()`.
    terrain_meshes: Arc<Vec<TerrainMeshData>>,

    /// Manual terrain output override to apply after the next update cycle.
    pending_terrain_meshes: Option<Arc<Vec<TerrainMeshData>>>,

    /// Prepared hillshade rasters for the last `update()`.
    hillshade_rasters: Arc<Vec<PreparedHillshadeRaster>>,

    /// Visible tiles produced by the tile layer (or set externally).
    visible_tiles: Arc<Vec<VisibleTile>>,

    // -- Per-frame layer output -------------------------------------------
    /// Tessellated vector meshes from the last `update()`.
    pub(crate) vector_meshes: Arc<Vec<VectorMeshData>>,

    /// Manual vector output override to apply after the next update cycle.
    pending_vector_meshes: Option<Arc<Vec<VectorMeshData>>>,

    /// 3D model instances collected from all visible
    /// [`ModelLayer`](crate::layers::ModelLayer)s during the last `update()`.
    pub(crate) model_instances: Arc<Vec<ModelInstance>>,

    /// Manual model output override to apply after the next update cycle.
    pending_model_instances: Option<Arc<Vec<ModelInstance>>>,

    /// Placed symbols after collision resolution.
    placed_symbols: Arc<Vec<PlacedSymbol>>,

    /// Symbol asset dependency state derived from placed symbols.
    symbol_assets: SymbolAssetRegistry,

    /// Stateful symbol placement engine.
    symbol_placement: SymbolPlacementEngine,

    /// Mutable per-feature state keyed by source id and feature id.
    feature_state: HashMap<FeatureStateId, FeatureState>,

    /// Hidden style-owned streamed vector source runtimes keyed by source id.
    streamed_vector_sources: HashMap<String, crate::layers::TileLayer>,

    /// Last per-style-layer streamed vector fingerprint used to detect data changes.
    streamed_vector_layer_fingerprints: HashMap<String, u64>,

    /// Tile-owned query payloads for streamed vector style layers.
    streamed_vector_query_payloads: HashMap<String, Vec<TileQueryPayload>>,

    /// Tile-owned symbol query payloads grouped by style layer.
    streamed_symbol_query_payloads: HashMap<String, Vec<SymbolQueryPayload>>,

    /// Tile-owned symbol dependency payloads grouped by style layer.
    streamed_symbol_dependency_payloads: HashMap<String, Vec<SymbolDependencyPayload>>,

    /// Streamed symbol layers that must regenerate on the next update.
    dirty_streamed_symbol_layers: HashSet<String>,

    /// Streamed symbol tiles that must regenerate on the next update.
    dirty_streamed_symbol_tiles: HashMap<String, HashSet<TileId>>,

    /// Visualization overlays collected from the layer stack.
    visualization_overlays: Arc<Vec<crate::visualization::VisualizationOverlay>>,

    /// Image overlays collected from the layer stack.
    image_overlays: Arc<Vec<crate::layers::ImageOverlayData>>,

    /// Active placeholder style applied to loading tiles.
    placeholder_style: PlaceholderStyle,

    /// Loading placeholders from the last update.
    loading_placeholders: Arc<Vec<LoadingPlaceholder>>,

    /// Monotonic time accumulator (seconds) for placeholder animation.
    placeholder_time: f64,

    /// Optional engine-owned interaction manager for automatic hover/leave/click
    /// lifecycle bookkeeping. Set via [`set_interaction_manager`](Self::set_interaction_manager).
    interaction_manager: Option<crate::interaction_manager::InteractionManager>,

    /// Sync-path per-layer vector tessellation cache.
    ///
    /// When no async pipeline is active, [`update_heavy_layers`](Self::update_heavy_layers)
    /// stores the most recent tessellation result per layer here and reuses it
    /// when neither the style, the feature data, nor the projection have changed.
    sync_vector_cache: HashMap<SyncVectorCacheKey, SyncVectorCacheEntry>,

    /// Cross-source tile request coordinator.
    ///
    /// Distributes a global per-frame request budget among raster, vector,
    /// and terrain tile sources so they don't compete for bandwidth.
    /// See [`TileRequestCoordinator`] for details.
    request_coordinator: TileRequestCoordinator,

    /// Camera-motion sampling and look-ahead configuration.
    camera_velocity_config: CameraVelocityConfig,

    /// Monotonic clock used for camera-motion sampling.
    camera_motion_time_seconds: f64,

    /// Recent camera-target samples in Web Mercator world space.
    camera_motion_samples: VecDeque<CameraMotionSample>,

    /// Smoothed camera pan velocity and translated viewport prediction.
    camera_motion_state: CameraMotionState,

    /// Per-frame fractional zoom delta used for zoom-direction prefetch.
    camera_zoom_delta: f64,

    /// Previous fractional zoom sample for zoom-direction tracking.
    previous_fractional_zoom: Option<f64>,

    /// Optional navigation route polyline for route-aware tile prefetch.
    ///
    /// When set, the tile update loop speculatively prefetches tiles along
    /// this route ahead of the camera position, spending any remaining
    /// speculative budget after viewport and zoom-direction prefetch.
    prefetch_route: Option<Vec<GeoCoord>>,

    /// Callback-based event subscription emitter.
    ///
    /// Events drained from the [`InteractionManager`] are dispatched to
    /// registered listeners each frame, in addition to being available
    /// via the poll-based [`drain_events`] path.
    event_emitter: crate::event_emitter::EventEmitter,

    /// Multi-touch gesture recognizer.
    ///
    /// Converts raw [`TouchContact`](crate::input::TouchContact) events
    /// into pan / zoom / rotate [`InputEvent`]s.
    gesture_recognizer: crate::gesture::GestureRecognizer,

    /// Optional user fog/atmosphere override.
    fog_config: Option<crate::style::FogConfig>,

    /// Pre-computed fog parameters for the current frame.
    computed_fog: crate::style::ComputedFog,

    /// Optional user lighting override.
    light_config: Option<crate::style::LightConfig>,

    /// Pre-computed lighting parameters for the current frame.
    computed_lighting: crate::style::ComputedLighting,

    /// Pre-computed shadow cascade parameters for the current frame.
    computed_shadow: crate::style::ComputedShadow,

    /// Optional user sky/atmosphere override.
    sky_config: Option<crate::style::SkyConfig>,

    /// Pre-computed sky parameters for the current frame.
    computed_sky: crate::style::ComputedSky,

    // -- Style transitions ------------------------------------------------
    /// Monotonic accumulated time (seconds) for style transitions.
    style_time: f64,

    /// Per-layer transition state for paint-property interpolation.
    layer_transitions:
        std::collections::HashMap<crate::style::StyleLayerId, crate::style::LayerTransitionState>,
}

// ---------------------------------------------------------------------------
// Default
// ---------------------------------------------------------------------------

impl Default for MapState {
    fn default() -> Self {
        let zero = WorldCoord::new(0.0, 0.0, 0.0);
        Self {
            camera: Camera::default(),
            constraints: CameraConstraints::default(),
            layers: LayerStack::new(),
            style: None,
            terrain: TerrainManager::new(TerrainConfig::default(), 256),
            animator: CameraAnimator::new(),
            data_update_interval: 0.15,
            data_update_elapsed: 0.0,
            async_pipeline: None,
            zoom_level: 0,
            viewport_bounds: WorldBounds::new(zero, zero),
            scene_viewport_bounds: WorldBounds::new(zero, zero),
            frustum: None,
            terrain_meshes: Arc::new(Vec::new()),
            pending_terrain_meshes: None,
            hillshade_rasters: Arc::new(Vec::new()),
            visible_tiles: Arc::new(Vec::new()),
            vector_meshes: Arc::new(Vec::new()),
            pending_vector_meshes: None,
            model_instances: Arc::new(Vec::new()),
            pending_model_instances: None,
            placed_symbols: Arc::new(Vec::new()),
            symbol_assets: SymbolAssetRegistry::new(),
            symbol_placement: SymbolPlacementEngine::new(),
            feature_state: HashMap::new(),
            streamed_vector_sources: HashMap::new(),
            streamed_vector_layer_fingerprints: HashMap::new(),
            streamed_vector_query_payloads: HashMap::new(),
            streamed_symbol_query_payloads: HashMap::new(),
            streamed_symbol_dependency_payloads: HashMap::new(),
            dirty_streamed_symbol_layers: HashSet::new(),
            dirty_streamed_symbol_tiles: HashMap::new(),
            visualization_overlays: Arc::new(Vec::new()),
            image_overlays: Arc::new(Vec::new()),
            placeholder_style: PlaceholderStyle::default(),
            loading_placeholders: Arc::new(Vec::new()),
            placeholder_time: 0.0,
            interaction_manager: None,
            sync_vector_cache: HashMap::new(),
            request_coordinator: TileRequestCoordinator::default(),
            camera_velocity_config: CameraVelocityConfig::default(),
            camera_motion_time_seconds: 0.0,
            camera_motion_samples: VecDeque::new(),
            camera_motion_state: CameraMotionState::default(),
            camera_zoom_delta: 0.0,
            previous_fractional_zoom: None,
            prefetch_route: None,
            event_emitter: crate::event_emitter::EventEmitter::new(),
            gesture_recognizer: crate::gesture::GestureRecognizer::new(),
            fog_config: None,
            computed_fog: crate::style::ComputedFog::default(),
            light_config: None,
            computed_lighting: crate::style::ComputedLighting::default(),
            computed_shadow: crate::style::ComputedShadow::default(),
            sky_config: None,
            computed_sky: crate::style::ComputedSky::default(),
            style_time: 0.0,
            layer_transitions: std::collections::HashMap::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Construction
// ---------------------------------------------------------------------------

impl MapState {
    /// Create a new map state with default camera and no terrain.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a map state with terrain support.
    ///
    /// # Arguments
    ///
    /// - `terrain_config` -- Terrain settings (enabled flag, mesh resolution,
    ///   elevation source, vertical exaggeration, skirt depth).
    /// - `terrain_cache_size` -- Maximum number of elevation grids to keep
    ///   in the LRU cache.
    pub fn with_terrain(terrain_config: TerrainConfig, terrain_cache_size: usize) -> Self {
        let zero = WorldCoord::new(0.0, 0.0, 0.0);
        Self {
            camera: Camera::default(),
            constraints: CameraConstraints::default(),
            layers: LayerStack::new(),
            style: None,
            terrain: TerrainManager::new(terrain_config, terrain_cache_size),
            animator: CameraAnimator::new(),
            data_update_interval: 0.15,
            data_update_elapsed: 0.0,
            async_pipeline: None,
            zoom_level: 0,
            viewport_bounds: WorldBounds::new(zero, zero),
            scene_viewport_bounds: WorldBounds::new(zero, zero),
            frustum: None,
            terrain_meshes: Arc::new(Vec::new()),
            pending_terrain_meshes: None,
            hillshade_rasters: Arc::new(Vec::new()),
            visible_tiles: Arc::new(Vec::new()),
            vector_meshes: Arc::new(Vec::new()),
            pending_vector_meshes: None,
            model_instances: Arc::new(Vec::new()),
            pending_model_instances: None,
            placed_symbols: Arc::new(Vec::new()),
            symbol_assets: SymbolAssetRegistry::new(),
            symbol_placement: SymbolPlacementEngine::new(),
            feature_state: HashMap::new(),
            streamed_vector_sources: HashMap::new(),
            streamed_vector_layer_fingerprints: HashMap::new(),
            streamed_vector_query_payloads: HashMap::new(),
            streamed_symbol_query_payloads: HashMap::new(),
            streamed_symbol_dependency_payloads: HashMap::new(),
            dirty_streamed_symbol_layers: HashSet::new(),
            dirty_streamed_symbol_tiles: HashMap::new(),
            visualization_overlays: Arc::new(Vec::new()),
            image_overlays: Arc::new(Vec::new()),
            placeholder_style: PlaceholderStyle::default(),
            loading_placeholders: Arc::new(Vec::new()),
            placeholder_time: 0.0,
            interaction_manager: None,
            sync_vector_cache: HashMap::new(),
            request_coordinator: TileRequestCoordinator::default(),
            camera_velocity_config: CameraVelocityConfig::default(),
            camera_motion_time_seconds: 0.0,
            camera_motion_samples: VecDeque::new(),
            camera_motion_state: CameraMotionState::default(),
            camera_zoom_delta: 0.0,
            previous_fractional_zoom: None,
            prefetch_route: None,
            event_emitter: crate::event_emitter::EventEmitter::new(),
            gesture_recognizer: crate::gesture::GestureRecognizer::new(),
            fog_config: None,
            computed_fog: crate::style::ComputedFog::default(),
            light_config: None,
            computed_lighting: crate::style::ComputedLighting::default(),
            computed_shadow: crate::style::ComputedShadow::default(),
            sky_config: None,
            computed_sky: crate::style::ComputedSky::default(),
            style_time: 0.0,
            layer_transitions: std::collections::HashMap::new(),
        }
    }

    // -- Accessors (derived state) ----------------------------------------

    /// Current integer zoom level (0-22).
    ///
    /// Derived from [`Camera::meters_per_pixel`] during [`update`](Self::update).
    /// Returns `0` before the first update.
    #[inline]
    pub fn zoom_level(&self) -> u8 {
        self.zoom_level
    }

    /// Continuous fractional zoom level (e.g. `8.73`).
    ///
    /// Derived from [`Camera::near_meters_per_pixel`] using the same
    /// formula as [`zoom_level`](Self::zoom_level), but without rounding
    /// to an integer.  Useful for debug displays and smooth zoom
    /// interpolation.
    #[inline]
    pub fn fractional_zoom(&self) -> f64 {
        let mpp = self.camera.near_meters_per_pixel();
        if mpp <= 0.0 || !mpp.is_finite() {
            return MAX_ZOOM as f64;
        }
        (WGS84_CIRCUMFERENCE / (mpp * TILE_PX))
            .log2()
            .clamp(0.0, MAX_ZOOM as f64)
    }

    /// Viewport bounding box in Web Mercator world space from the last
    /// [`update`](Self::update).
    ///
    /// Includes an overscan margin for tile prefetching.
    #[inline]
    pub fn viewport_bounds(&self) -> &WorldBounds {
        &self.viewport_bounds
    }

    /// Read-only access to the camera-motion prediction configuration.
    #[inline]
    pub fn camera_velocity_config(&self) -> &CameraVelocityConfig {
        &self.camera_velocity_config
    }

    /// Replace the camera-motion prediction configuration.
    pub fn set_camera_velocity_config(&mut self, config: CameraVelocityConfig) {
        self.camera_velocity_config = config;
        self.trim_camera_motion_samples();
        self.recompute_camera_motion_state();
    }

    /// Smoothed camera pan velocity and translated viewport prediction.
    #[inline]
    pub fn camera_motion_state(&self) -> &CameraMotionState {
        &self.camera_motion_state
    }

    /// Predicted viewport bounds after the configured look-ahead interval.
    #[inline]
    pub fn predicted_viewport_bounds(&self) -> &WorldBounds {
        &self.camera_motion_state.predicted_viewport_bounds
    }

    /// Viewport bounding box in the active planar scene projection.
    #[inline]
    pub fn scene_viewport_bounds(&self) -> &WorldBounds {
        &self.scene_viewport_bounds
    }

    /// View frustum from the last [`update`](Self::update).
    ///
    /// `None` only before the first `update()` call.
    #[inline]
    pub fn frustum(&self) -> Option<&Frustum> {
        self.frustum.as_ref()
    }

    /// Renderer/world origin used by the current render compatibility path.
    ///
    /// This remains Web Mercator backed for the current raster/terrain stack,
    /// even when the camera itself uses a different planar projection.
    #[inline]
    pub fn renderer_world_origin(&self) -> glam::DVec3 {
        let (x, y) = self.mercator_camera_world();
        glam::DVec3::new(x, y, 0.0)
    }

    /// Active scene origin in the camera's currently selected planar
    /// projection.
    ///
    /// Projection-specialized geometry paths such as terrain, vectors,
    /// symbols, models, and Bevy geo-entities should use this origin so
    /// their world coordinates remain aligned under non-Mercator planar
    /// projections.
    #[inline]
    pub fn scene_world_origin(&self) -> glam::DVec3 {
        self.camera.target_world()
    }

    /// Terrain meshes produced during the last [`update`](Self::update).
    ///
    /// Empty when terrain is disabled or no elevation data is cached.
    #[inline]
    pub fn terrain_meshes(&self) -> &[TerrainMeshData] {
        &self.terrain_meshes
    }

    /// Prepared DEM-derived hillshade rasters from the last update.
    #[inline]
    pub fn hillshade_rasters(&self) -> &[PreparedHillshadeRaster] {
        &self.hillshade_rasters
    }

    /// Visible tiles from the last [`update`](Self::update).
    #[inline]
    pub fn visible_tiles(&self) -> &[VisibleTile] {
        &self.visible_tiles
    }

    /// Loading placeholders from the last [`update`](Self::update).
    ///
    /// One entry per visible tile that has no data yet.  Empty when all
    /// visible tiles are loaded.
    #[inline]
    pub fn loading_placeholders(&self) -> &[LoadingPlaceholder] {
        &self.loading_placeholders
    }

    /// Active placeholder style.
    #[inline]
    pub fn placeholder_style(&self) -> &PlaceholderStyle {
        &self.placeholder_style
    }

    /// Replace the placeholder style.
    pub fn set_placeholder_style(&mut self, style: PlaceholderStyle) {
        self.placeholder_style = style;
    }

    /// Read-only access to the cross-source tile request coordinator's
    /// most recent diagnostics.
    pub fn coordinator_stats(&self) -> &CoordinatorStats {
        self.request_coordinator.stats()
    }

    /// Read-only access to the cross-source coordinator configuration.
    pub fn coordinator_config(&self) -> &CoordinatorConfig {
        self.request_coordinator.config()
    }

    /// Replace the cross-source coordinator configuration.
    ///
    /// Takes effect on the next frame.  Set `global_request_budget` to
    /// 0 to disable coordination entirely.
    pub fn set_coordinator_config(&mut self, config: CoordinatorConfig) {
        self.request_coordinator.set_config(config);
    }

    /// Set an optional navigation route for route-aware tile prefetch.
    ///
    /// When set, the tile update loop will speculatively prefetch tiles
    /// along the route ahead of the current camera position, spending
    /// remaining speculative budget after viewport-prediction and
    /// zoom-direction prefetch.
    ///
    /// The route should be a polyline of geographic coordinates ordered
    /// from origin to destination.  Pass an empty slice or call
    /// [`clear_prefetch_route`](Self::clear_prefetch_route) to disable.
    pub fn set_prefetch_route(&mut self, route: Vec<GeoCoord>) {
        if route.len() < 2 {
            self.prefetch_route = None;
        } else {
            self.prefetch_route = Some(route);
        }
    }

    /// Clear the navigation route used for route-aware tile prefetch.
    pub fn clear_prefetch_route(&mut self) {
        self.prefetch_route = None;
    }

    /// Read-only access to the active prefetch route, if any.
    #[inline]
    pub fn prefetch_route(&self) -> Option<&[GeoCoord]> {
        self.prefetch_route.as_deref()
    }

    /// Return a diagnostics snapshot for the first visible tile layer, if any.
    pub fn tile_pipeline_diagnostics(&self) -> Option<TilePipelineDiagnostics> {
        use crate::layers::TileLayer;

        for layer in self.layers.iter() {
            if !layer.visible() {
                continue;
            }
            let Some(tile_layer) = layer.as_any().downcast_ref::<TileLayer>() else {
                continue;
            };

            let visible = tile_layer.visible_tiles();
            let visible_loaded_tiles = visible
                .tiles
                .iter()
                .filter(|tile| tile.data.is_some())
                .count();
            let visible_fallback_tiles = visible
                .tiles
                .iter()
                .filter(|tile| tile.is_fallback() && tile.data.is_some())
                .count();
            let visible_missing_tiles = visible
                .tiles
                .iter()
                .filter(|tile| tile.data.is_none())
                .count();
            let visible_overzoomed_tiles = visible
                .tiles
                .iter()
                .filter(|tile| tile.is_overzoomed())
                .count();

            return Some(TilePipelineDiagnostics {
                layer_name: tile_layer.name().to_owned(),
                visible_tiles: visible.len(),
                visible_loaded_tiles,
                visible_fallback_tiles,
                visible_missing_tiles,
                visible_overzoomed_tiles,
                selection_stats: tile_layer.last_selection_stats().clone(),
                counters: tile_layer.counters().clone(),
                cache_stats: tile_layer.cache_stats(),
                source_diagnostics: tile_layer.source_diagnostics(),
            });
        }

        None
    }

    /// Return recent tile lifecycle diagnostics for the first visible tile layer, if any.
    pub fn tile_lifecycle_diagnostics(&self) -> Option<TileLifecycleDiagnostics> {
        use crate::layers::TileLayer;

        for layer in self.layers.iter() {
            if !layer.visible() {
                continue;
            }
            let Some(tile_layer) = layer.as_any().downcast_ref::<TileLayer>() else {
                continue;
            };
            return Some(tile_layer.lifecycle_diagnostics());
        }

        None
    }

    /// Return the effective background Colour from the top-most visible
    /// [`BackgroundLayer`](crate::layers::BackgroundLayer), if any.
    ///
    /// This gives renderers a backend-owned clear colour similar to
    /// MapLibre's background layer instead of relying only on hard-coded
    /// renderer defaults.
    pub fn background_color(&self) -> Option<[f32; 4]> {
        use crate::layers::BackgroundLayer;

        let mut color = None;
        for layer in self.layers.iter() {
            if !layer.visible() {
                continue;
            }
            if let Some(background) = layer.as_any().downcast_ref::<BackgroundLayer>() {
                color = Some(background.effective_color());
            }
        }
        color
    }

    /// Return the effective hillshade parameters from the top-most visible
    /// [`HillshadeLayer`](crate::layers::HillshadeLayer), if any.
    pub fn hillshade(&self) -> Option<crate::layers::HillshadeParams> {
        use crate::layers::HillshadeLayer;

        let mut params = None;
        for layer in self.layers.iter() {
            if !layer.visible() {
                continue;
            }
            if let Some(hillshade) = layer.as_any().downcast_ref::<HillshadeLayer>() {
                params = Some(hillshade.effective_params());
            }
        }
        params
    }

    /// Set the fog/atmosphere configuration override.
    ///
    /// When set, the provided [`FogConfig`](crate::style::FogConfig) values
    /// override the automatic pitch-based fog computation.  `None` fields
    /// in the config fall back to the auto-computed defaults.
    ///
    /// Pass `None` to revert to fully automatic fog.
    pub fn set_fog(&mut self, config: Option<crate::style::FogConfig>) {
        self.fog_config = config;
    }

    /// Return the current fog configuration override, if any.
    pub fn fog(&self) -> Option<&crate::style::FogConfig> {
        self.fog_config.as_ref()
    }

    /// Return the pre-computed fog parameters for the current frame.
    ///
    /// These are recomputed each frame during [`update()`](Self::update)
    /// from camera state, the optional [`FogConfig`](crate::style::FogConfig),
    /// and the background colour.  Renderers should read these values
    /// directly instead of duplicating the fog math.
    pub fn computed_fog(&self) -> &crate::style::ComputedFog {
        &self.computed_fog
    }

    /// Set the lighting configuration override.
    ///
    /// When set, the provided [`LightConfig`](crate::style::LightConfig)
    /// values override the style document's `"lights"` configuration and
    /// the engine defaults.
    ///
    /// Pass `None` to revert to the style document's or default lighting.
    pub fn set_lights(&mut self, config: Option<crate::style::LightConfig>) {
        self.light_config = config;
    }

    /// Return the current lighting configuration override, if any.
    pub fn lights(&self) -> Option<&crate::style::LightConfig> {
        self.light_config.as_ref()
    }

    /// Return the pre-computed lighting parameters for the current frame.
    ///
    /// Recomputed each frame during [`update()`](Self::update).
    /// Renderers should read these values directly instead of hardcoding
    /// light directions.
    pub fn computed_lighting(&self) -> &crate::style::ComputedLighting {
        &self.computed_lighting
    }

    /// Return the pre-computed shadow cascade parameters for the current frame.
    ///
    /// [`ComputedShadow::enabled`](crate::style::ComputedShadow::enabled) is
    /// `true` only when the directional light has `cast_shadows = true` and
    /// lighting is not in flat mode.
    pub fn computed_shadow(&self) -> &crate::style::ComputedShadow {
        &self.computed_shadow
    }

    /// Set the sky / atmosphere configuration override.
    ///
    /// When set, the provided [`SkyConfig`](crate::style::SkyConfig)
    /// enables a procedural sky background.  Pass `None` to disable.
    pub fn set_sky(&mut self, config: Option<crate::style::SkyConfig>) {
        self.sky_config = config;
    }

    /// Return the current sky configuration override, if any.
    pub fn sky(&self) -> Option<&crate::style::SkyConfig> {
        self.sky_config.as_ref()
    }

    /// Return the pre-computed sky parameters for the current frame.
    ///
    /// Recomputed each frame during [`update()`](Self::update).
    pub fn computed_sky(&self) -> &crate::style::ComputedSky {
        &self.computed_sky
    }

    /// Current monotonic style time (seconds), used for transition
    /// interpolation.
    pub fn style_time(&self) -> f64 {
        self.style_time
    }

    /// Per-layer transition state map.
    pub fn layer_transitions(
        &self,
    ) -> &std::collections::HashMap<crate::style::StyleLayerId, crate::style::LayerTransitionState>
    {
        &self.layer_transitions
    }

    /// Resolve current transitioned property values for a layer.
    ///
    /// Returns `None` if no transition state has been recorded for the
    /// given layer yet.
    pub fn resolved_transitions(
        &self,
        layer_id: &str,
    ) -> Option<crate::style::ResolvedTransitions> {
        self.layer_transitions
            .get(layer_id)
            .map(|ts| ts.resolve(self.style_time))
    }

    /// Override the visible tile set for this frame.
    pub fn set_visible_tiles(&mut self, tiles: Vec<VisibleTile>) {
        self.visible_tiles = Arc::new(tiles);
    }

    /// Override the terrain meshes for this frame (useful for testing).
    pub fn set_terrain_meshes(&mut self, meshes: Vec<TerrainMeshData>) {
        let meshes = Arc::new(meshes);
        self.pending_terrain_meshes = Some(meshes.clone());
        self.terrain_meshes = meshes;
    }

    /// Override the prepared hillshade rasters for this frame (useful for testing).
    pub fn set_hillshade_rasters(&mut self, rasters: Vec<PreparedHillshadeRaster>) {
        self.hillshade_rasters = Arc::new(rasters);
    }

    // -- Camera accessors -------------------------------------------------

    /// Immutable reference to the camera.
    #[inline]
    pub fn camera(&self) -> &Camera {
        &self.camera
    }

    /// Set the camera viewport dimensions (logical pixels).
    pub fn set_viewport(&mut self, width: u32, height: u32) {
        self.camera.set_viewport(width, height);
    }

    /// Set the camera target geographic coordinate.
    ///
    /// Longitude is normalized to `[-180, 180)` to prevent the camera
    /// from drifting into a different world copy, which would cause
    /// tile selection to diverge and tiles to stop rendering.
    pub fn set_camera_target(&mut self, target: GeoCoord) {
        if !target.lat.is_finite() || !target.lon.is_finite() {
            return;
        }
        let wrapped = GeoCoord::from_lat_lon(target.lat, wrap_lon_180(target.lon));
        self.camera.set_target(wrapped);
    }

    /// Set the camera distance from the target in meters.
    pub fn set_camera_distance(&mut self, distance: f64) {
        if !distance.is_finite() || distance <= 0.0 {
            return;
        }
        self.camera.set_distance(distance);
    }

    /// Set the camera pitch in radians.
    pub fn set_camera_pitch(&mut self, pitch: f64) {
        if !pitch.is_finite() {
            return;
        }
        self.camera.set_pitch(pitch);
    }

    /// Set the camera yaw / bearing in radians.
    pub fn set_camera_yaw(&mut self, yaw: f64) {
        if !yaw.is_finite() {
            return;
        }
        self.camera.set_yaw(yaw);
    }

    /// Set the camera projection mode (perspective / orthographic).
    pub fn set_camera_mode(&mut self, mode: CameraMode) {
        self.camera.set_mode(mode);
    }

    /// Set the camera geographic projection used by camera/world helpers.
    pub fn set_camera_projection(&mut self, projection: CameraProjection) {
        self.camera.set_projection(projection);
    }

    /// Set the vertical field-of-view in radians (perspective mode).
    pub fn set_camera_fov_y(&mut self, fov_y: f64) {
        if !fov_y.is_finite() || fov_y <= 0.0 {
            return;
        }
        self.camera.set_fov_y(fov_y);
    }

    // -- Constraint accessors ---------------------------------------------

    /// Immutable reference to the camera constraints.
    #[inline]
    pub fn constraints(&self) -> &CameraConstraints {
        &self.constraints
    }

    /// Set the maximum camera pitch in radians.
    pub fn set_max_pitch(&mut self, max_pitch: f64) {
        if !max_pitch.is_finite() || max_pitch <= 0.0 {
            return;
        }
        self.constraints.max_pitch = max_pitch;
    }

    /// Set the minimum camera distance in meters.
    pub fn set_min_distance(&mut self, min_distance: f64) {
        if !min_distance.is_finite() || min_distance <= 0.0 {
            return;
        }
        self.constraints.min_distance = min_distance;
    }

    /// Set the maximum camera distance in meters.
    pub fn set_max_distance(&mut self, max_distance: f64) {
        if !max_distance.is_finite() || max_distance <= 0.0 {
            return;
        }
        self.constraints.max_distance = max_distance;
    }

    // -- Layer accessors---------------------------------------------------

    /// Immutable reference to the layer stack.
    #[inline]
    pub fn layers(&self) -> &LayerStack {
        &self.layers
    }

    /// Add a layer to the top of the stack.
    pub fn push_layer(&mut self, layer: Box<dyn crate::layer::Layer>) {
        self.layers.push(layer);
        self.style = None;
    }

    /// Insert or replace a named grid-scalar visualization layer.
    pub fn set_grid_scalar(
        &mut self,
        name: impl Into<String>,
        grid: crate::visualization::GeoGrid,
        field: crate::visualization::ScalarField2D,
        ramp: crate::visualization::ColorRamp,
    ) {
        let name = name.into();
        if let Some(index) = self.layers.index_of(&name) {
            if let Some(layer) = self.layers.get_mut(index) {
                if let Some(existing) = layer
                    .as_any_mut()
                    .downcast_mut::<crate::visualization::GridScalarLayer>()
                {
                    existing.grid = grid;
                    existing.field = field;
                    existing.ramp = ramp;
                    self.style = None;
                    return;
                }
            }
        }
        let layer = Box::new(crate::visualization::GridScalarLayer::new(
            name.clone(),
            grid,
            field,
            ramp,
        ));
        self.replace_or_push_named_layer(&name, layer);
    }

    /// Insert or replace a named grid-extrusion visualization layer.
    pub fn set_grid_extrusion(
        &mut self,
        name: impl Into<String>,
        grid: crate::visualization::GeoGrid,
        field: crate::visualization::ScalarField2D,
        ramp: crate::visualization::ColorRamp,
        params: crate::visualization::ExtrusionParams,
    ) {
        let name = name.into();
        if let Some(index) = self.layers.index_of(&name) {
            if let Some(layer) = self.layers.get_mut(index) {
                if let Some(existing) = layer
                    .as_any_mut()
                    .downcast_mut::<crate::visualization::GridExtrusionLayer>()
                {
                    existing.grid = grid;
                    existing.field = field;
                    existing.ramp = ramp;
                    existing.params = params;
                    self.style = None;
                    return;
                }
            }
        }
        let layer = Box::new(
            crate::visualization::GridExtrusionLayer::new(name.clone(), grid, field, ramp)
                .with_params(params),
        );
        self.replace_or_push_named_layer(&name, layer);
    }

    /// Insert or replace a named instanced-column visualization layer.
    pub fn set_instanced_columns(
        &mut self,
        name: impl Into<String>,
        columns: crate::visualization::ColumnInstanceSet,
        ramp: crate::visualization::ColorRamp,
    ) {
        let name = name.into();
        if let Some(index) = self.layers.index_of(&name) {
            if let Some(layer) = self.layers.get_mut(index) {
                if let Some(existing) = layer
                    .as_any_mut()
                    .downcast_mut::<crate::visualization::InstancedColumnLayer>()
                {
                    existing.columns = columns;
                    existing.ramp = ramp;
                    self.style = None;
                    return;
                }
            }
        }
        let layer = Box::new(crate::visualization::InstancedColumnLayer::new(
            name.clone(),
            columns,
            ramp,
        ));
        self.replace_or_push_named_layer(&name, layer);
    }

    /// Insert or replace a named point-cloud visualization layer.
    pub fn set_point_cloud(
        &mut self,
        name: impl Into<String>,
        points: crate::visualization::PointInstanceSet,
        ramp: crate::visualization::ColorRamp,
    ) {
        let name = name.into();
        if let Some(index) = self.layers.index_of(&name) {
            if let Some(layer) = self.layers.get_mut(index) {
                if let Some(existing) = layer
                    .as_any_mut()
                    .downcast_mut::<crate::visualization::PointCloudLayer>()
                {
                    existing.points = points;
                    existing.ramp = ramp;
                    self.style = None;
                    return;
                }
            }
        }
        let layer = Box::new(crate::visualization::PointCloudLayer::new(
            name.clone(),
            points,
            ramp,
        ));
        self.replace_or_push_named_layer(&name, layer);
    }

    /// Return the currently attached style, if any.
    #[inline]
    pub fn style(&self) -> Option<&MapStyle> {
        self.style.as_ref()
    }

    /// Return the currently attached style document, if any.
    #[inline]
    pub fn style_document(&self) -> Option<&StyleDocument> {
        self.style.as_ref().map(MapStyle::document)
    }

    /// Replace the current style runtime and re-evaluate terrain + layer state.
    pub fn set_style(&mut self, style: MapStyle) -> Result<(), StyleError> {
        self.apply_style_document(style.document())?;
        self.style = Some(style);
        Ok(())
    }

    /// Replace the current style document and re-evaluate terrain + layer state.
    pub fn set_style_document(&mut self, document: StyleDocument) -> Result<(), StyleError> {
        self.set_style(MapStyle::from_document(document))
    }

    /// Mutate the current style document in place and then re-apply it.
    pub fn with_style_mut<R>(
        &mut self,
        mutate: impl FnOnce(&mut StyleDocument) -> R,
    ) -> Result<Option<R>, StyleError> {
        let mut style: MapStyle = match self.style.take() {
            Some(s) => s,
            None => return Ok(None),
        };
        let result = mutate(style.document_mut());
        self.apply_style_document(style.document())?;
        self.style = Some(style);
        Ok(Some(result))
    }

    /// Re-evaluate the currently attached style document, if any.
    pub fn reapply_style(&mut self) -> Result<bool, StyleError> {
        let style: MapStyle = match self.style.take() {
            Some(s) => s,
            None => return Ok(false),
        };
        self.apply_style_document(style.document())?;
        self.style = Some(style);
        Ok(true)
    }

    // -- Terrain accessors ------------------------------------------------

    /// Immutable reference to the terrain manager.
    #[inline]
    pub fn terrain(&self) -> &TerrainManager {
        &self.terrain
    }

    /// Replace the terrain manager with a new configuration.
    pub fn set_terrain(&mut self, terrain: TerrainManager) {
        self.terrain = terrain;
        if self.style.is_some() {
            self.style = None;
        }
    }

    // -- Animator accessor ------------------------------------------------

    /// Immutable reference to the camera animator.
    #[inline]
    pub fn animator(&self) -> &CameraAnimator {
        &self.animator
    }

    /// Whether any camera animation is currently active.
    #[inline]
    pub fn is_animating(&self) -> bool {
        self.animator.is_active()
    }

    // -- Data update throttle during animation ----------------------------

    /// Set the minimum interval (seconds) between full terrain + layer
    /// updates while a coordinated camera animation is active.
    pub fn set_data_update_interval(&mut self, interval: f64) {
        self.data_update_interval = interval.max(0.0);
    }

    /// Current data-update throttle interval in seconds.
    #[inline]
    pub fn data_update_interval(&self) -> f64 {
        self.data_update_interval
    }

    // -- Async task pool --------------------------------------------------

    /// Inject an async task pool for offloading heavy data pipeline work.
    pub fn set_task_pool(&mut self, pool: Arc<dyn DataTaskPool>) {
        self.async_pipeline = Some(AsyncDataPipeline::new(pool));
    }

    /// Remove the async task pool, reverting to synchronous execution.
    pub fn clear_task_pool(&mut self) {
        self.async_pipeline = None;
    }

    /// Whether an async task pool is currently active.
    #[inline]
    pub fn has_async_pipeline(&self) -> bool {
        self.async_pipeline.is_some()
    }

    // -- Frame output accessors -------------------------------------------

    /// Tessellated vector meshes from the last update.
    #[inline]
    pub fn vector_meshes(&self) -> &[VectorMeshData] {
        &self.vector_meshes
    }

    /// 3D model instances from the last update.
    #[inline]
    pub fn model_instances(&self) -> &[ModelInstance] {
        &self.model_instances
    }

    /// Placed symbols from the last update.
    #[inline]
    pub fn placed_symbols(&self) -> &[PlacedSymbol] {
        &self.placed_symbols
    }

    /// Symbol asset dependency state for the last update.
    #[inline]
    pub fn symbol_assets(&self) -> &SymbolAssetRegistry {
        &self.symbol_assets
    }

    /// Look up feature state for a source-local feature id.
    pub fn feature_state(&self, source_id: &str, feature_id: &str) -> Option<&FeatureState> {
        self.feature_state
            .get(&FeatureStateId::new(source_id, feature_id))
    }

    /// Replace feature state for a source-local feature id.
    pub fn set_feature_state(
        &mut self,
        source_id: impl Into<String>,
        feature_id: impl Into<String>,
        state: FeatureState,
    ) {
        self.feature_state
            .insert(FeatureStateId::new(source_id, feature_id), state);
    }

    /// Set a single feature-state property.
    pub fn set_feature_state_property(
        &mut self,
        source_id: impl Into<String>,
        feature_id: impl Into<String>,
        key: impl Into<String>,
        value: crate::geometry::PropertyValue,
    ) {
        self.feature_state
            .entry(FeatureStateId::new(source_id, feature_id))
            .or_default()
            .insert(key.into(), value);
    }

    /// Remove feature state for a source-local feature id.
    pub fn remove_feature_state(
        &mut self,
        source_id: &str,
        feature_id: &str,
    ) -> Option<FeatureState> {
        self.feature_state
            .remove(&FeatureStateId::new(source_id, feature_id))
    }

    /// Clear all stored feature state.
    pub fn clear_feature_state(&mut self) {
        self.feature_state.clear();
    }

    /// Resolve a style layer's paint properties for a specific feature's
    /// current state.
    ///
    /// This is the primary convenience method for hover/selection restyling:
    /// it looks up the named style layer, retrieves the feature's current
    /// state from the internal store, and evaluates all paint properties
    /// through the [`StyleEvalContextFull`] path.
    ///
    /// Returns `None` when:
    /// - no style document is attached
    /// - the layer id does not exist in the style document
    /// - the layer type does not produce a [`VectorStyle`] (background,
    ///   hillshade, raster, model)
    ///
    /// # Example
    ///
    /// ```ignore
    /// map.set_feature_state_property("source", "feat-42", "hover", PropertyValue::Bool(true));
    /// if let Some(style) = map.resolve_feature_style("buildings", "source", "feat-42") {
    ///     // `style` has paint values resolved with hover=true.
    /// }
    /// ```
    pub fn resolve_feature_style(
        &self,
        style_layer_id: &str,
        source_id: &str,
        feature_id: &str,
    ) -> Option<VectorStyle> {
        use crate::style::StyleEvalContextFull;

        let document = self.style_document()?;
        let style_layer = document.layer(style_layer_id)?;
        let empty_state: FeatureState = HashMap::new();
        let state = self
            .feature_state
            .get(&FeatureStateId::new(source_id, feature_id))
            .unwrap_or(&empty_state);
        let ctx = StyleEvalContextFull::new(self.fractional_zoom() as f32, state);
        style_layer.resolve_style_with_feature_state(&ctx)
    }

    /// Attach an interaction manager for automatic hover/leave/click lifecycle.
    ///
    /// Once set, the host feeds raw pointer events into the manager (via
    /// [`interaction_manager_mut`](Self::interaction_manager_mut)) and drains
    /// high-level [`InteractionEvent`](crate::InteractionEvent)s each frame.
    pub fn set_interaction_manager(
        &mut self,
        manager: crate::interaction_manager::InteractionManager,
    ) {
        self.interaction_manager = Some(manager);
    }

    /// Remove the attached interaction manager, returning it if present.
    pub fn take_interaction_manager(
        &mut self,
    ) -> Option<crate::interaction_manager::InteractionManager> {
        self.interaction_manager.take()
    }

    /// Read-only access to the attached interaction manager.
    pub fn interaction_manager(&self) -> Option<&crate::interaction_manager::InteractionManager> {
        self.interaction_manager.as_ref()
    }

    /// Mutable access to the attached interaction manager.
    ///
    /// Use this to feed pointer events and drain emitted interaction events.
    pub fn interaction_manager_mut(
        &mut self,
    ) -> Option<&mut crate::interaction_manager::InteractionManager> {
        self.interaction_manager.as_mut()
    }

    // -- Event subscription (callback-based) ------------------------------

    /// Subscribe to interaction events of a given kind.
    ///
    /// Returns a [`ListenerId`](crate::event_emitter::ListenerId) for
    /// later removal via [`off`](Self::off).
    pub fn on<F>(
        &mut self,
        kind: crate::interaction::InteractionEventKind,
        callback: F,
    ) -> crate::event_emitter::ListenerId
    where
        F: Fn(&crate::interaction::InteractionEvent) + Send + Sync + 'static,
    {
        self.event_emitter.on(kind, callback)
    }

    /// Subscribe to a single occurrence of an interaction event kind.
    ///
    /// The listener is automatically removed after the first dispatch.
    pub fn once<F>(
        &mut self,
        kind: crate::interaction::InteractionEventKind,
        callback: F,
    ) -> crate::event_emitter::ListenerId
    where
        F: Fn(&crate::interaction::InteractionEvent) + Send + Sync + 'static,
    {
        self.event_emitter.once(kind, callback)
    }

    /// Unsubscribe a previously registered event listener.
    pub fn off(&mut self, id: crate::event_emitter::ListenerId) -> bool {
        self.event_emitter.off(id)
    }

    /// Dispatch interaction events to registered listeners.
    ///
    /// Call this after draining events from the interaction manager.
    /// Events are forwarded to all matching `on` / `once` callbacks.
    pub fn dispatch_events(&mut self, events: &[crate::interaction::InteractionEvent]) {
        self.event_emitter.dispatch(events);
    }

    /// Mutable access to the event emitter for advanced use cases.
    pub fn event_emitter_mut(&mut self) -> &mut crate::event_emitter::EventEmitter {
        &mut self.event_emitter
    }

    /// Invalidate placed-symbol tiles that depend on the given image id.
    pub fn invalidate_symbol_image_dependency(&mut self, image_id: &str) -> usize {
        self.invalidate_symbol_dependency_tiles(|deps| deps.images.contains(image_id))
    }

    /// Invalidate placed-symbol tiles that depend on the given glyph.
    pub fn invalidate_symbol_glyph_dependency(
        &mut self,
        font_stack: &str,
        codepoint: char,
    ) -> usize {
        let glyph = crate::symbols::GlyphKey {
            font_stack: font_stack.to_owned(),
            codepoint,
        };
        self.invalidate_symbol_dependency_tiles(|deps| deps.glyphs.contains(&glyph))
    }

    /// Override the vector meshes for this frame (useful for testing).
    pub fn set_vector_meshes(&mut self, meshes: Vec<VectorMeshData>) {
        let meshes = Arc::new(meshes);
        self.pending_vector_meshes = Some(meshes.clone());
        self.vector_meshes = meshes;
    }

    /// Override the model instances for this frame (useful for testing).
    pub fn set_model_instances(&mut self, instances: Vec<ModelInstance>) {
        let instances = Arc::new(instances);
        self.pending_model_instances = Some(instances.clone());
        self.model_instances = instances;
    }

    /// Override the placed symbols for this frame (useful for testing).
    pub fn set_placed_symbols(&mut self, symbols: Vec<PlacedSymbol>) {
        self.placed_symbols = Arc::new(symbols);
        self.symbol_assets
            .rebuild_from_symbols(&self.placed_symbols);
    }

    // =====================================================================
    // Update cycle
    // =====================================================================

    /// Recompute all derived state with an explicit delta-time (seconds).
    pub fn update_with_dt(&mut self, dt: f64) {
        let was_flying = self.animator.is_flying() || self.animator.is_easing();

        self.update_camera(dt);

        let is_flying = self.animator.is_flying() || self.animator.is_easing();

        // -- Async path: dispatch + poll (cheap every frame) ----------------
        if self.async_pipeline.is_some() {
            self.dispatch_data_requests();
            self.poll_completed_results(dt);
        } else {
            // -- Synchronous path (fallback) ---------------------------------
            //
            // Tile layer updates (poll completed HTTP responses, recompute
            // the visible tile set, issue new requests) are cheap and must
            // run every frame so that:
            //   1. Completed tile downloads are picked up promptly.
            //   2. The visible tile set tracks the current camera position.
            //   3. Tiles transition from "pending" to "loaded" without lag.
            //
            // Expensive work (terrain meshing, vector tessellation, symbol
            // placement, model collection) is throttled during animation.
            let animation_active = is_flying;

            // Always update tile layers every frame.
            self.update_tile_layers();

            if animation_active && self.data_update_interval > 0.0 {
                self.data_update_elapsed += dt;
                if self.data_update_elapsed >= self.data_update_interval {
                    self.data_update_elapsed = 0.0;
                    self.update_heavy_layers(dt);
                }
            } else {
                self.data_update_elapsed = 0.0;
                self.update_heavy_layers(dt);
            }
        }

        // Post-animation catch-up: ensure a full data update fires on the
        // first frame after a fly-to / ease-to animation finishes.
        if was_flying && !is_flying && self.async_pipeline.is_none() {
            self.update_tile_layers();
            self.update_heavy_layers(dt);
        }

        // -- Style transition clock (lightweight, every frame) -------------
        self.style_time += dt.max(0.0);

        // -- Loading placeholders (lightweight, every frame) ----------------
        self.placeholder_time += dt;
        self.loading_placeholders = Arc::new(PlaceholderGenerator::generate(
            &self.visible_tiles,
            &self.placeholder_style,
            self.placeholder_time,
        ));

        if let Err(e) = self.sync_attached_style_runtime() {
            log::warn!("style sync error: {e:?}");
        }

        self.apply_pending_frame_overrides();

        // -- Recompute fog params for this frame ----------------------------
        {
            let bg = self.background_color().unwrap_or([1.0, 1.0, 1.0, 1.0]);
            let pitch = self.camera.pitch();
            let distance = self.camera.distance();
            let style_fog = self.style.as_ref().and_then(|s| s.document().fog());
            let effective_fog = self.fog_config.as_ref().or(style_fog);
            self.computed_fog = crate::style::compute_fog(pitch, distance, bg, effective_fog);
        }

        // -- Recompute lighting params for this frame -----------------------
        {
            let style_lights = self.style.as_ref().and_then(|s| s.document().lights());
            let effective_lights = self.light_config.as_ref().or(style_lights);
            let default_lights = crate::style::LightConfig::default();
            let config = effective_lights.unwrap_or(&default_lights);
            self.computed_lighting = crate::style::compute_lighting(config);

            // -- Recompute shadow cascades when enabled ---------------------
            if self.computed_lighting.shadows_enabled {
                let vp = self.camera.view_projection_matrix();
                let dir = self.computed_lighting.directional_dir;
                let cam_dist = self.camera.distance();
                self.computed_shadow =
                    crate::style::compute_shadow_cascades(&vp, dir, cam_dist, &config.shadow);
            } else {
                self.computed_shadow = crate::style::ComputedShadow::default();
            }
        }

        // -- Recompute sky params for this frame ----------------------------
        {
            let style_sky = self.style.as_ref().and_then(|s| s.document().sky());
            let effective_sky = self.sky_config.as_ref().or(style_sky);
            if let Some(sky) = effective_sky {
                // Fallback sun direction from the effective light config.
                let style_lights = self.style.as_ref().and_then(|s| s.document().lights());
                let effective_lights = self.light_config.as_ref().or(style_lights);
                let fallback_sun = effective_lights
                    .map(|l| l.directional.direction)
                    .unwrap_or([210.0, 45.0]);
                self.computed_sky = crate::style::compute_sky(sky, fallback_sun);
            } else {
                self.computed_sky = crate::style::ComputedSky::default();
            }
        }
    }

    /// Forward an input event to the camera controller.
    ///
    /// [`Touch`](InputEvent::Touch) events are routed through the
    /// built-in [`GestureRecognizer`](crate::gesture::GestureRecognizer),
    /// which converts multi-touch sequences into pan / zoom / rotate
    /// events before forwarding them to the camera controller.
    pub fn handle_input(&mut self, event: InputEvent) {
        if let InputEvent::Touch(contact) = event {
            let derived = self.gesture_recognizer.process(contact);
            for e in derived {
                CameraController::handle_event(&mut self.camera, e, &self.constraints);
            }
            return;
        }
        CameraController::handle_event(&mut self.camera, event, &self.constraints);
    }

    /// Access the gesture recognizer (e.g. to call [`reset`](crate::gesture::GestureRecognizer::reset)).
    pub fn gesture_recognizer(&self) -> &crate::gesture::GestureRecognizer {
        &self.gesture_recognizer
    }

    /// Convenience: calls `update_with_dt(1.0 / 60.0)`.
    pub fn update(&mut self) {
        self.update_with_dt(1.0 / 60.0);
    }

    /// Begin a fly-to animation.
    pub fn fly_to(&mut self, options: crate::camera_animator::FlyToOptions) {
        self.animator.start_fly_to(&mut self.camera, &options);
    }

    /// Begin an ease-to animation.
    pub fn ease_to(&mut self, options: crate::camera_animator::EaseToOptions) {
        self.animator.start_ease_to(&mut self.camera, &options);
    }

    /// Immediately jump the camera to the given state.
    pub fn jump_to(
        &mut self,
        target: GeoCoord,
        distance: f64,
        pitch: Option<f64>,
        yaw: Option<f64>,
    ) {
        self.animator.cancel();
        self.camera.set_target(target);
        self.camera.set_distance(distance);
        if let Some(p) = pitch {
            self.camera.set_pitch(p);
        }
        if let Some(y) = yaw {
            self.camera.set_yaw(y);
        }
    }

    /// Tick the camera animator and recompute zoom / viewport / frustum.
    pub fn update_camera(&mut self, dt: f64) {
        self.animator.tick(&mut self.camera, dt);

        // Normalize the camera longitude after every animation tick to
        // keep it within [-180, 180).  Without this, fly-to and ease-to
        // animations that cross the antimeridian can leave the camera in
        // a different world copy, causing viewport_bounds and tile
        // selection to diverge and tiles to stop rendering.  This matches
        // the Mapbox/MapLibre wrap-jump handling behavior.
        {
            let target = *self.camera.target();
            let wrapped_lon = wrap_lon_180(target.lon);
            if (wrapped_lon - target.lon).abs() > 1e-12 {
                self.camera
                    .set_target(GeoCoord::from_lat_lon(target.lat, wrapped_lon));
            }
        }

        let mpp = self.camera.meters_per_pixel();
        self.zoom_level = Self::mpp_to_zoom(mpp);
        self.viewport_bounds = self.compute_viewport_bounds();
        self.scene_viewport_bounds = self.compute_scene_viewport_bounds();
        self.frustum = Some(Frustum::from_view_projection(
            &self.camera.view_projection_matrix(),
        ));
        self.update_camera_motion_state(dt);

        let fractional_zoom = self.fractional_zoom();
        self.camera_zoom_delta = self
            .previous_fractional_zoom
            .map_or(0.0, |previous| fractional_zoom - previous);
        self.previous_fractional_zoom = Some(fractional_zoom);
    }

    /// Build a detached per-frame snapshot for renderers.
    pub fn frame_output(&self) -> FrameOutput {
        FrameOutput {
            view_projection: self.camera.view_projection_matrix(),
            frustum: self.frustum.clone(),
            tiles: Arc::clone(&self.visible_tiles),
            terrain: Arc::clone(&self.terrain_meshes),
            hillshade: Arc::clone(&self.hillshade_rasters),
            vectors: Arc::clone(&self.vector_meshes),
            models: Arc::clone(&self.model_instances),
            symbols: Arc::clone(&self.placed_symbols),
            visualization: Arc::clone(&self.visualization_overlays),
            placeholders: Arc::clone(&self.loading_placeholders),
            image_overlays: Arc::clone(&self.image_overlays),
            zoom_level: self.zoom_level,
        }
    }

    /// Query the terrain elevation at a geographic coordinate.
    pub fn elevation_at(&self, coord: &GeoCoord) -> Option<f64> {
        self.terrain.elevation_at(coord)
    }

    /// Unproject a screen pixel to a geographic coordinate (flat ground).
    pub fn screen_to_geo(&self, px: f64, py: f64) -> Option<GeoCoord> {
        self.camera.screen_to_geo(px, py)
    }

    /// Project a geographic coordinate to a screen-space pixel position.
    ///
    /// Returns `(px, py)` in logical pixels with `(0, 0)` at the
    /// top-left corner of the viewport, or `None` if the point is
    /// behind the camera.
    pub fn geo_to_screen(&self, geo: &GeoCoord) -> Option<(f64, f64)> {
        self.camera.geo_to_screen(geo)
    }

    /// Fit the camera to a geographic bounding box.
    ///
    /// Computes the center and zoom level that make the entire bounding
    /// box visible, accounting for optional padding.  Depending on
    /// `options.animate`, the transition may be animated (`fly_to`) or
    /// instant (`jump_to`).
    pub fn fit_bounds(&mut self, bounds: &GeoBounds, options: &FitBoundsOptions) {
        let center = bounds.center();

        // Project SW and NE to world meters.
        let sw_world = WebMercator::project_clamped(&bounds.sw());
        let ne_world = WebMercator::project_clamped(&bounds.ne());

        let dx = (ne_world.position.x - sw_world.position.x).abs();
        let dy = (ne_world.position.y - sw_world.position.y).abs();

        // Subtract padding from the effective viewport.
        let vw =
            (self.camera.viewport_width() as f64 - options.padding.left - options.padding.right)
                .max(1.0);
        let vh =
            (self.camera.viewport_height() as f64 - options.padding.top - options.padding.bottom)
                .max(1.0);

        // Meters-per-pixel required to fit the bounds.
        let mpp_x = dx / vw;
        let mpp_y = dy / vh;
        let mpp = mpp_x.max(mpp_y);

        // Convert mpp to zoom.
        let zoom = if mpp <= 0.0 || !mpp.is_finite() {
            MAX_ZOOM as f64
        } else {
            (WGS84_CIRCUMFERENCE / (mpp * TILE_PX))
                .log2()
                .clamp(0.0, MAX_ZOOM as f64)
        };

        // Clamp to max_zoom.
        let zoom = match options.max_zoom {
            Some(mz) => zoom.min(mz),
            None => zoom,
        };

        if options.animate {
            let fly = crate::camera_animator::FlyToOptions {
                center: Some(center),
                zoom: Some(zoom),
                bearing: options.bearing,
                pitch: options.pitch,
                duration: options.duration,
                ..Default::default()
            };
            self.fly_to(fly);
        } else {
            // Convert zoom to distance.
            let is_perspective = matches!(self.camera.mode(), CameraMode::Perspective);
            let distance = {
                let mpp = WGS84_CIRCUMFERENCE / (2.0_f64.powf(zoom) * TILE_PX);
                let vis_h = mpp * self.camera.viewport_height().max(1) as f64;
                if is_perspective {
                    vis_h / (2.0 * (self.camera.fov_y() / 2.0).tan())
                } else {
                    vis_h / 2.0
                }
            };
            self.jump_to(center, distance, options.pitch, options.bearing);
        }
    }

    /// Cast a ray and intersect with the flat ground plane (z = 0).
    pub fn ray_to_geo(&self, origin: glam::DVec3, direction: glam::DVec3) -> Option<GeoCoord> {
        if direction.z.abs() < 1e-12 {
            return None;
        }
        let t = -origin.z / direction.z;
        if t < 0.0 {
            return None;
        }
        let hit = origin + direction * t;
        let world = self.camera.target_world();
        let world_hit = WorldCoord::new(hit.x + world.x, hit.y + world.y, 0.0);
        Some(self.camera.projection().unproject(&world_hit))
    }

    /// Cast a ray and intersect with the terrain surface.
    ///
    /// Falls back to flat ground intersection if terrain is disabled or
    /// no intersection is found.
    pub fn ray_to_geo_on_terrain(
        &self,
        origin: glam::DVec3,
        direction: glam::DVec3,
    ) -> Option<GeoCoord> {
        if !self.terrain.enabled() {
            return self.ray_to_geo(origin, direction);
        }

        let world = self.camera.target_world();
        let steps = 64;
        let max_t = self.camera.distance() * 4.0;
        let step = max_t / steps as f64;

        let mut prev_above = true;
        for i in 0..=steps {
            let t = step * i as f64;
            let p = origin + direction * t;
            let world_hit = WorldCoord::new(p.x + world.x, p.y + world.y, p.z);
            let geo = self.camera.projection().unproject(&world_hit);
            let elev = self.terrain.elevation_at(&geo).unwrap_or(0.0);
            let above = p.z >= elev;
            if !above && prev_above && i > 0 {
                // Linear interpolation between previous and current step.
                let prev_t = step * (i - 1) as f64;
                let prev_p = origin + direction * prev_t;
                let prev_world = WorldCoord::new(prev_p.x + world.x, prev_p.y + world.y, prev_p.z);
                let prev_geo = self.camera.projection().unproject(&prev_world);
                let prev_elev = self.terrain.elevation_at(&prev_geo).unwrap_or(0.0);
                let prev_height = prev_p.z - prev_elev;
                let curr_height = p.z - elev;
                let frac = prev_height / (prev_height - curr_height);
                let hit_t = prev_t + (t - prev_t) * frac;
                let hit = origin + direction * hit_t;
                let hit_world = WorldCoord::new(hit.x + world.x, hit.y + world.y, hit.z);
                return Some(self.camera.projection().unproject(&hit_world));
            }
            prev_above = above;
        }
        // Fallback to flat ground.
        self.ray_to_geo(origin, direction)
    }

    /// Cast a ray and intersect with the flat ground plane, ignoring terrain.
    pub fn ray_to_flat_geo(&self, origin: glam::DVec3, direction: glam::DVec3) -> Option<GeoCoord> {
        self.ray_to_geo(origin, direction)
    }

    /// Screen-to-geo through the terrain surface.
    pub fn screen_to_geo_on_terrain(&self, px: f64, py: f64) -> Option<GeoCoord> {
        let (origin, direction) = self.camera.screen_to_ray(px, py);
        self.ray_to_geo_on_terrain(origin, direction)
    }

    // =====================================================================
    // Synchronous layer update (fallback when no async pipeline)
    // =====================================================================

    // Full synchronous layer update (tile + heavy layers).
    //
    // Used by the non-animation path and the async dispatch path.
    // =====================================================================
    // Async dispatch + poll
    // =====================================================================

    // =====================================================================
    // Private helpers
    // =====================================================================

    /// Camera target in Web Mercator world coordinates.
    fn mercator_camera_world(&self) -> (f64, f64) {
        let w = WebMercator::project(self.camera.target());
        (w.position.x, w.position.y)
    }

    fn update_camera_motion_state(&mut self, dt: f64) {
        self.camera_motion_time_seconds += dt.max(0.0);

        let current_wrapped = self.mercator_camera_world();
        let current_target = if let Some(last) = self.camera_motion_samples.back() {
            glam::DVec2::new(
                last.target_world.x
                    + heavy_layers::wrapped_world_delta(current_wrapped.0 - last.target_world.x),
                current_wrapped.1,
            )
        } else {
            glam::DVec2::new(current_wrapped.0, current_wrapped.1)
        };

        self.camera_motion_samples.push_back(CameraMotionSample {
            time_seconds: self.camera_motion_time_seconds,
            target_world: current_target,
        });
        self.trim_camera_motion_samples();
        self.recompute_camera_motion_state();
    }

    fn trim_camera_motion_samples(&mut self) {
        let max_samples = self.camera_velocity_config.sample_window.max(1) + 1;
        while self.camera_motion_samples.len() > max_samples {
            self.camera_motion_samples.pop_front();
        }
    }

    fn recompute_camera_motion_state(&mut self) {
        let pan_velocity_world = if let (Some(first), Some(last)) = (
            self.camera_motion_samples.front(),
            self.camera_motion_samples.back(),
        ) {
            let dt = last.time_seconds - first.time_seconds;
            if dt > 1e-9 {
                (last.target_world - first.target_world) / dt
            } else {
                glam::DVec2::ZERO
            }
        } else {
            glam::DVec2::ZERO
        };

        let current_wrapped = self.mercator_camera_world();
        let current_target_world = glam::DVec2::new(current_wrapped.0, current_wrapped.1);
        let look_ahead = self.camera_velocity_config.look_ahead_seconds.max(0.0);
        let predicted_delta = pan_velocity_world * look_ahead;

        self.camera_motion_state = CameraMotionState {
            pan_velocity_world,
            predicted_target_world: current_target_world + predicted_delta,
            predicted_viewport_bounds: heavy_layers::translated_world_bounds(
                &self.viewport_bounds,
                predicted_delta,
            ),
        };
    }

    /// Camera target in the active scene projection.
    /// Convert meters-per-pixel to an integer zoom level.
    fn mpp_to_zoom(mpp: f64) -> u8 {
        if mpp <= 0.0 || !mpp.is_finite() {
            return MAX_ZOOM;
        }
        let z = (WGS84_CIRCUMFERENCE / (mpp * TILE_PX)).log2();
        (z.round() as u8).min(MAX_ZOOM)
    }

    /// Compute the viewport bounding box in Web Mercator world coordinates.
    fn compute_viewport_bounds(&self) -> WorldBounds {
        use rustial_math::WebMercator;

        let w = self.camera.viewport_width() as f64;
        let h = self.camera.viewport_height() as f64;

        if w <= 0.0 || h <= 0.0 {
            let zero = WorldCoord::new(0.0, 0.0, 0.0);
            return WorldBounds::new(zero, zero);
        }

        let cam = &self.camera;

        // Check if camera supports orthographic bounds directly.
        if cam.mode() == CameraMode::Orthographic {
            let half_w = cam.distance() * (w / h).max(1.0);
            let half_h = cam.distance() / (w / h).min(1.0);
            let target = WebMercator::project(cam.target());
            let overscan = 1.3;
            return WorldBounds::new(
                WorldCoord::new(
                    target.position.x - half_w * overscan,
                    target.position.y - half_h * overscan,
                    0.0,
                ),
                WorldCoord::new(
                    target.position.x + half_w * overscan,
                    target.position.y + half_h * overscan,
                    0.0,
                ),
            );
        }

        let mut min_x = f64::MAX;
        let mut min_y = f64::MAX;
        let mut max_x = f64::MIN;
        let mut max_y = f64::MIN;
        let mut any_hit = false;

        for (sx, sy) in viewport_sample_points(w, h) {
            if let Some(geo) = cam.screen_to_geo(sx, sy) {
                let world = WebMercator::project_clamped(&geo);
                min_x = min_x.min(world.position.x);
                min_y = min_y.min(world.position.y);
                max_x = max_x.max(world.position.x);
                max_y = max_y.max(world.position.y);
                any_hit = true;
            }
        }

        if !any_hit {
            let target = WebMercator::project(cam.target());
            let mpp = cam.meters_per_pixel();
            let half_w = mpp * w * 0.5;
            let half_h = mpp * h * 0.5;
            return WorldBounds::new(
                WorldCoord::new(target.position.x - half_w, target.position.y - half_h, 0.0),
                WorldCoord::new(target.position.x + half_w, target.position.y + half_h, 0.0),
            );
        }

        let overscan = perspective_viewport_overscan(cam.pitch());
        let cx = (min_x + max_x) * 0.5;
        let cy = (min_y + max_y) * 0.5;
        let hw = (max_x - min_x) * 0.5 * overscan;
        let hh = (max_y - min_y) * 0.5 * overscan;
        WorldBounds::new(
            WorldCoord::new(cx - hw, cy - hh, 0.0),
            WorldCoord::new(cx + hw, cy + hh, 0.0),
        )
    }

    /// Compute the viewport bounding box in the active scene projection.
    fn compute_scene_viewport_bounds(&self) -> WorldBounds {
        let w = self.camera.viewport_width() as f64;
        let h = self.camera.viewport_height() as f64;

        if w <= 0.0 || h <= 0.0 {
            let zero = WorldCoord::new(0.0, 0.0, 0.0);
            return WorldBounds::new(zero, zero);
        }

        let cam = &self.camera;
        let proj = cam.projection();

        if cam.mode() == CameraMode::Orthographic {
            let half_w = cam.distance() * (w / h).max(1.0);
            let half_h = cam.distance() / (w / h).min(1.0);
            let target = proj.project(cam.target());
            let overscan = 1.3;
            return WorldBounds::new(
                WorldCoord::new(
                    target.position.x - half_w * overscan,
                    target.position.y - half_h * overscan,
                    0.0,
                ),
                WorldCoord::new(
                    target.position.x + half_w * overscan,
                    target.position.y + half_h * overscan,
                    0.0,
                ),
            );
        }

        let mut min_x = f64::MAX;
        let mut min_y = f64::MAX;
        let mut max_x = f64::MIN;
        let mut max_y = f64::MIN;
        let mut any_hit = false;

        for (sx, sy) in viewport_sample_points(w, h) {
            if let Some(geo) = cam.screen_to_geo(sx, sy) {
                let world = proj.project(&geo);
                min_x = min_x.min(world.position.x);
                min_y = min_y.min(world.position.y);
                max_x = max_x.max(world.position.x);
                max_y = max_y.max(world.position.y);
                any_hit = true;
            }
        }

        if !any_hit {
            let target = proj.project(cam.target());
            let mpp = cam.meters_per_pixel();
            let half_w = mpp * w * 0.5;
            let half_h = mpp * h * 0.5;
            return WorldBounds::new(
                WorldCoord::new(target.position.x - half_w, target.position.y - half_h, 0.0),
                WorldCoord::new(target.position.x + half_w, target.position.y + half_h, 0.0),
            );
        }

        let overscan = perspective_viewport_overscan(cam.pitch());
        let cx = (min_x + max_x) * 0.5;
        let cy = (min_y + max_y) * 0.5;
        let hw = (max_x - min_x) * 0.5 * overscan;
        let hh = (max_y - min_y) * 0.5 * overscan;
        WorldBounds::new(
            WorldCoord::new(cx - hw, cy - hh, 0.0),
            WorldCoord::new(cx + hw, cy + hh, 0.0),
        )
    }

    /// Re-evaluate the attached style runtime at the current zoom.
    fn sync_attached_style_runtime(&mut self) -> Result<(), StyleError> {
        let Some(style) = self.style.as_ref() else {
            return Ok(());
        };
        let doc = style.document();
        let ctx = crate::style::StyleEvalContext {
            zoom: self.fractional_zoom() as f32,
        };
        let now = self.style_time;

        // Walk each style layer and update transition state.
        for style_layer in doc.layers() {
            let (layer_id, transition_spec, opacity, color, secondary_color, width, height, base) =
                extract_transition_props(style_layer, ctx, &doc.transition());
            let state = self
                .layer_transitions
                .entry(layer_id.to_owned())
                .or_insert_with(|| {
                    crate::style::LayerTransitionState::from_initial(
                        transition_spec,
                        opacity,
                        color,
                        secondary_color,
                        width,
                        height,
                        base,
                    )
                });
            state.update(now, opacity, color, secondary_color, width, height, base);
        }
        Ok(())
    }

    /// Replace an existing layer with the same name or push a new one.
    fn replace_or_push_named_layer(&mut self, name: &str, layer: Box<dyn crate::layer::Layer>) {
        if let Some(index) = self.layers.index_of(name) {
            let _ = self.layers.remove(index);
            self.layers.insert(index, layer);
        } else {
            self.layers.push(layer);
        }
        self.style = None;
    }
}

// =========================================================================
// Free helper functions
// =========================================================================

/// Extract the transitionable paint-property values from a [`StyleLayer`]
/// at the given zoom.
///
/// Returns `(id, spec, opacity, color, secondary_color, width, height, base)`.
fn extract_transition_props<'a>(
    layer: &'a crate::style::StyleLayer,
    ctx: crate::style::StyleEvalContext,
    global_transition: &crate::style::TransitionSpec,
) -> (
    &'a str,
    crate::style::TransitionSpec,
    f32,
    [f32; 4],
    [f32; 4],
    f32,
    f32,
    f32,
) {
    use crate::style::StyleLayer;

    let meta = layer.meta();
    let spec = if meta.transition.is_active() {
        meta.transition
    } else {
        *global_transition
    };
    let opacity = meta.opacity.evaluate_with_context(ctx);

    let transparent: [f32; 4] = [0.0, 0.0, 0.0, 0.0];
    let (color, secondary_color, width, height, base) = match layer {
        StyleLayer::Fill(f) => (
            f.fill_color.evaluate_with_context(ctx),
            f.outline_color.evaluate_with_context(ctx),
            f.outline_width.evaluate_with_context(ctx),
            0.0,
            0.0,
        ),
        StyleLayer::Line(l) => (
            l.color.evaluate_with_context(ctx),
            transparent,
            l.width.evaluate_with_context(ctx),
            0.0,
            0.0,
        ),
        StyleLayer::Circle(c) => (
            c.color.evaluate_with_context(ctx),
            c.stroke_color.evaluate_with_context(ctx),
            c.radius.evaluate_with_context(ctx),
            0.0,
            0.0,
        ),
        StyleLayer::FillExtrusion(e) => (
            e.color.evaluate_with_context(ctx),
            transparent,
            0.0,
            e.height.evaluate_with_context(ctx),
            e.base.evaluate_with_context(ctx),
        ),
        StyleLayer::Symbol(s) => (
            s.color.evaluate_with_context(ctx),
            s.halo_color.evaluate_with_context(ctx),
            s.size.evaluate_with_context(ctx),
            0.0,
            0.0,
        ),
        StyleLayer::Heatmap(h) => (
            h.color.evaluate_with_context(ctx),
            transparent,
            h.radius.evaluate_with_context(ctx),
            0.0,
            0.0,
        ),
        StyleLayer::Background(b) => (
            b.color.evaluate_with_context(ctx),
            transparent,
            0.0,
            0.0,
            0.0,
        ),
        _ => (transparent, transparent, 0.0, 0.0, 0.0),
    };

    (
        meta.id.as_str(),
        spec,
        opacity,
        color,
        secondary_color,
        width,
        height,
        base,
    )
}