rustial-renderer-wgpu 1.0.0

Pure WGPU renderer for the rustial 2.5D map engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
// ---------------------------------------------------------------------------
//! # Top-level WGPU renderer
//!
//! [`WgpuMapRenderer`] is the single entry-point for drawing the map with
//! a pure-WGPU backend.  The host application creates it once during
//! initialisation and calls [`render`](WgpuMapRenderer::render) (or the
//! richer [`render_full`](WgpuMapRenderer::render_full)) each frame.
//!
//! ## Ownership model
//!
//! The renderer **does not** own the `wgpu::Device`, `wgpu::Queue`, or
//! surface.  These are provided by the host (typically via winit + WGPU
//! surface setup) and passed in by reference.  This keeps the renderer
//! framework-agnostic: it works identically inside a winit event loop,
//! an egui integration, or a headless offscreen test.
//!
//! ## Camera-relative rendering
//!
//! All world-space positions (tiles, terrain, vectors, models) are
#![allow(clippy::many_single_char_names)]
//! transformed to *camera-relative* f32 coordinates before upload.
//! The camera's world-space origin is subtracted on the CPU so that
//! vertices near the camera are close to `(0, 0, 0)`.  This avoids
//! catastrophic f32 precision loss when the camera is far from the
//! Web Mercator origin (e.g. at longitude 170 degrees, x ~ 19 million meters).
//!
//! The view-projection matrix is similarly computed relative to the
//! camera origin and uploaded as a single shared uniform buffer.
//!
//! ## GPU resource layout
//!
//! | Resource | Lifetime | Notes |
//! |----------|----------|-------|
//! | Pipelines (tile, terrain, vector, model) | Renderer | Created once |
//! | Uniform buffer + bind groups | Renderer | One buffer, four BGs (shared layout) |
//! | Tile atlas (`TileAtlas`) | Renderer | Grows lazily, evicted per-frame |
//! | Page bind groups | Renderer | Rebuilt when atlas pages are added |
//! | Tile batch buffers | Cached | Invalidated when visible set or camera origin changes |
//! | Vector batch buffers | Cached | Invalidated when mesh data or camera origin changes |
//! | Terrain batch buffers (fallback) | Per-frame | Only used for non-standard projections |
//! | Model mesh buffers | Cached | Keyed by `ModelMeshKey` fingerprint |
//! | Model transform buffers | Cached | Invalidated when instance set or camera origin changes |
//! | Shared terrain grid meshes | Cached | One per resolution, reused across all tiles |
//! | Elevation textures | Cached | Per-tile R32Float, invalidated on generation change |
//! | Depth texture | Renderer | Recreated on `resize()` |
//! | Sampler | Renderer | Bilinear, clamp-to-edge |
//!
//! ## Frame lifecycle
//!
//! ```text
//! render_full(params)
//!   1. Upload view-proj uniform
//!   2. Upload new tile textures into the atlas
//!   3. Mark visible tiles + terrain tiles as used
//!   4. Cache model mesh GPU buffers (avoids re-upload)
//!   5. Build batched geometry (tiles, terrain, vectors)
//!   6. Begin render pass (clear colour + depth)
//!      a. Draw terrain batches  -- OR --  flat tile batches
//!      b. Draw vector overlays
//!      c. Draw 3D model instances
//!   7. Submit command buffer
//!   8. Atlas end-of-frame eviction
//! ```
// ---------------------------------------------------------------------------

use crate::gpu::batch::{
    build_circle_batch, build_fill_batch, build_fill_extrusion_batch,
    build_fill_pattern_batch, build_heatmap_batch, build_hillshade_batches,
    build_line_batch, build_line_pattern_batch, build_placeholder_batches,
    build_symbol_batch, build_terrain_batches, build_tile_batches,
    build_vector_batch, find_terrain_texture_actual, CircleBatchEntry,
    FillBatchEntry, FillExtrusionBatchEntry, FillPatternBatchEntry,
    HeatmapBatchEntry, HillshadeBatch, LineBatchEntry,
    LinePatternBatchEntry, SymbolBatchEntry, TerrainBatch, TilePageBatches,
    VectorBatchEntry,
};
use crate::gpu::depth::create_depth_texture;
use crate::gpu::column_vertex::{ColumnInstanceData, ColumnVertex};
use crate::gpu::grid_extrusion_vertex::GridExtrusionVertex;
use crate::gpu::grid_scalar_vertex::GridScalarVertex;
use crate::gpu::image_overlay_vertex::ImageOverlayVertex;
use crate::gpu::model_vertex::ModelVertex;
use crate::gpu::terrain_buffers::TerrainInteractionBuffers;
use crate::gpu::terrain_grid_vertex::TerrainGridVertex;
use crate::gpu::tile_atlas::TileAtlas;
use crate::painter::{PainterPass, PainterPlan};
use crate::pipeline::circle_pipeline::CirclePipeline;
use crate::pipeline::column_pipeline::ColumnPipeline;
use crate::pipeline::fill_extrusion_pipeline::FillExtrusionPipeline;
use crate::pipeline::fill_pattern_pipeline::FillPatternPipeline;
use crate::pipeline::fill_pipeline::FillPipeline;
use crate::pipeline::grid_scalar_pipeline::GridScalarPipeline;
use crate::pipeline::grid_extrusion_pipeline::GridExtrusionPipeline;
use crate::pipeline::heatmap_colormap_pipeline::HeatmapColormapPipeline;
use crate::pipeline::heatmap_pipeline::HeatmapPipeline;
use crate::pipeline::hillshade_pipeline::HillshadePipeline;
use crate::pipeline::image_overlay_pipeline::ImageOverlayPipeline;
use crate::pipeline::line_pipeline::LinePipeline;
use crate::pipeline::line_pattern_pipeline::LinePatternPipeline;
use crate::pipeline::model_pipeline::ModelPipeline;
use crate::pipeline::symbol_pipeline::SymbolPipeline;
use crate::pipeline::terrain_data_pipeline::TerrainDataPipeline;
use crate::pipeline::terrain_pipeline::TerrainPipeline;
use crate::pipeline::tile_pipeline::TilePipeline;
use crate::pipeline::uniforms::ViewProjUniform;
use crate::pipeline::vector_pipeline::VectorPipeline;
use glam::{DVec3, Mat4};
use rustial_engine::{
    materialize_terrain_mesh, DecodedImage, LayerId, MapState, ModelInstance, TerrainMeshData,
    TileData, VectorMeshData, VectorRenderMode, VisibleTile, VisualizationOverlay,
};
use rustial_engine as rustial_math;
use rustial_engine::TileId;
use std::sync::Arc;
use wgpu::util::DeviceExt;

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct TerrainTileUniform {
    geo_bounds: [f32; 4],
    scene_origin: [f32; 4],
    elev_params: [f32; 4],
    elev_region: [f32; 4],
}

struct SharedTerrainGridMesh {
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    index_count: u32,
}

struct CachedHeightTexture {
    generation: u64,
    view: wgpu::TextureView,
}

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct GridScalarUniform {
    origin_counts: [f32; 4],
    grid_params: [f32; 4],
    scene_origin: [f32; 4],
    value_params: [f32; 4],
    base_altitude: [f32; 4],
}

struct SharedColumnMesh {
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    index_count: u32,
}

struct CachedGridScalarOverlay {
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    index_count: u32,
    vertex_count: usize,
    #[allow(dead_code)]
    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    #[allow(dead_code)]
    scalar_texture: wgpu::Texture,
    #[allow(dead_code)]
    ramp_texture: wgpu::Texture,
    generation: u64,
    value_generation: u64,
    ramp_fingerprint: u64,
    grid_fingerprint: u64,
    terrain_fingerprint: u64,
    projection: rustial_engine::CameraProjection,
    origin_key: [i64; 3],
}

struct CachedGridExtrusionOverlay {
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    index_count: u32,
    vertex_count: usize,
    generation: u64,
    value_generation: u64,
    origin_key: [i64; 3],
    grid_fingerprint: u64,
    params_fingerprint: u64,
    ramp_fingerprint: u64,
    terrain_fingerprint: u64,
}

struct CachedColumnOverlay {
    instance_buffer: wgpu::Buffer,
    instance_count: u32,
    generation: u64,
    origin_key: [i64; 3],
    columns_fingerprint: u64,
    ramp_fingerprint: u64,
    instance_data: Vec<ColumnInstanceData>,
}

struct CachedPointCloudOverlay {
    instance_buffer: wgpu::Buffer,
    instance_count: u32,
    generation: u64,
    origin_key: [i64; 3],
    points_fingerprint: u64,
    ramp_fingerprint: u64,
    instance_data: Vec<ColumnInstanceData>,
}

/// Per-frame visualization cache activity recorded during the last render.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct VisualizationPerfStats {
    /// Number of grid-scalar overlay cache rebuilds.
    pub grid_scalar_rebuilds: u32,
    /// Number of grid-scalar value-texture updates.
    pub grid_scalar_value_updates: u32,
    /// Number of grid-extrusion overlay rebuilds.
    pub grid_extrusion_rebuilds: u32,
    /// Number of grid-extrusion vertex-buffer updates.
    pub grid_extrusion_value_updates: u32,
    /// Number of column overlay rebuilds.
    pub column_rebuilds: u32,
    /// Number of partial column buffer writes.
    pub column_partial_writes: u32,
    /// Number of changed contiguous column ranges written this frame.
    pub column_partial_write_ranges: u32,
    /// Number of point-cloud overlay rebuilds.
    pub point_cloud_rebuilds: u32,
    /// Number of point-cloud partial retained writes.
    pub point_cloud_partial_writes: u32,
    /// Number of changed contiguous point-cloud ranges written this frame.
    pub point_cloud_partial_write_ranges: u32,
}

/// Cached per-tile terrain uniform buffer + bind group.
///
/// Matches MapLibre's approach of retaining per-tile GPU state across
/// frames and only recreating when the tile's data or the camera origin
/// changes.  This avoids allocating a fresh `wgpu::Buffer` and
/// `wgpu::BindGroup` for every terrain tile on every frame.
struct CachedTerrainTileBind {
    #[allow(dead_code)]
    uniform_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    /// Quantised scene origin used when this entry was created.
    origin_key: [i64; 3],
    /// Elevation data generation when this entry was created.
    generation: u64,
}

/// Cache key for per-tile terrain uniform/bind-group entries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct TerrainTileBindKey {
    tile: TileId,
    /// Which pipeline family created this entry.
    pipeline: TerrainPipelineKind,
}

/// Distinguish terrain vs terrain-data vs hillshade pipeline bind groups.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum TerrainPipelineKind {
    Terrain,
    TerrainData,
    Hillshade,
}

/// Dirty-tracking state for the terrain-data interaction pass.
///
/// Mirrors MapLibre's `terrainFacilitator` pattern: the depth/coordinate
/// framebuffers are only redrawn when the VP matrix or the visible terrain
/// set has changed, rather than unconditionally every frame.
struct TerrainDataDirtyState {
    /// Whether an explicit dirty flag has been set (e.g. after resize).
    dirty: bool,
    /// Last VP matrix (f32, column-major) that was rendered into the
    /// terrain-data buffers.
    last_vp: [f32; 16],
    /// Tile set fingerprint (sorted tile IDs + generations).
    last_terrain_fingerprint: u64,
}

impl Default for TerrainDataDirtyState {
    fn default() -> Self {
        Self {
            dirty: true,
            last_vp: [0.0; 16],
            last_terrain_fingerprint: 0,
        }
    }
}

impl TerrainDataDirtyState {
    /// Check whether the terrain-data pass needs to be redrawn.
    fn needs_update(
        &self,
        vp: &glam::DMat4,
        terrain_meshes: &[TerrainMeshData],
    ) -> bool {
        if self.dirty {
            return true;
        }
        let vp_f32 = vp.to_cols_array().map(|v| v as f32);
        if vp_f32 != self.last_vp {
            return true;
        }
        let fp = Self::terrain_fingerprint(terrain_meshes);
        fp != self.last_terrain_fingerprint
    }

    /// Record that the terrain-data pass was just rendered with these inputs.
    fn mark_clean(
        &mut self,
        vp: &glam::DMat4,
        terrain_meshes: &[TerrainMeshData],
    ) {
        self.dirty = false;
        self.last_vp = vp.to_cols_array().map(|v| v as f32);
        self.last_terrain_fingerprint = Self::terrain_fingerprint(terrain_meshes);
    }

    fn terrain_fingerprint(terrain_meshes: &[TerrainMeshData]) -> u64 {
        let mut h: u64 = terrain_meshes.len() as u64;
        for mesh in terrain_meshes {
            h = h
                .wrapping_mul(31)
                .wrapping_add(mesh.tile.zoom as u64)
                .wrapping_mul(31)
                .wrapping_add(mesh.tile.x as u64)
                .wrapping_mul(31)
                .wrapping_add(mesh.tile.y as u64)
                .wrapping_mul(31)
                .wrapping_add(mesh.generation);
        }
        h
    }
}

fn diff_column_instance_ranges(
    old: &[ColumnInstanceData],
    new: &[ColumnInstanceData],
) -> Vec<std::ops::Range<usize>> {
    if old.len() != new.len() {
        return if new.is_empty() { Vec::new() } else { vec![0..new.len()] };
    }

    let mut ranges = Vec::new();
    let mut current_start: Option<usize> = None;

    for (index, (old_item, new_item)) in old.iter().zip(new.iter()).enumerate() {
        if old_item != new_item {
            if current_start.is_none() {
                current_start = Some(index);
            }
        } else if let Some(start) = current_start.take() {
            ranges.push(start..index);
        }
    }

    if let Some(start) = current_start {
        ranges.push(start..new.len());
    }

    ranges
}

/// Cache key for tile batch buffers.  When the visible tile set and camera
/// origin haven't changed, the GPU buffers from the previous frame are
/// reused instead of being rebuilt.
#[derive(Debug, Clone, PartialEq)]
struct TileBatchCacheKey {
    /// Ordered list of (target, actual, fade_opacity_bits) tuples.
    ///
    /// `fade_opacity` is part of the key because tile vertex opacity is
    /// baked into the cached tile batch geometry.  Omitting it would allow
    /// a retained batch to freeze an in-progress fade transition until some
    /// unrelated input invalidated the cache.
    tiles: Vec<(TileId, TileId, u32)>,
    /// Camera origin quantised to avoid float drift invalidation.
    origin: [i64; 3],
    /// Active projection.
    projection: rustial_engine::CameraProjection,
}

impl TileBatchCacheKey {
    fn new(
        visible_tiles: &[VisibleTile],
        camera_origin: DVec3,
        projection: rustial_engine::CameraProjection,
    ) -> Self {
        let tiles: Vec<(TileId, TileId, u32)> = visible_tiles
            .iter()
            .map(|vt| (vt.target, vt.actual, vt.fade_opacity.to_bits()))
            .collect();
        let origin = [
            (camera_origin.x * 100.0) as i64,
            (camera_origin.y * 100.0) as i64,
            (camera_origin.z * 100.0) as i64,
        ];
        Self { tiles, origin, projection }
    }
}

/// Cache key for vector batch buffers.  Captures a fingerprint of the
/// vector mesh data so that unchanged layers reuse their GPU buffers.
#[derive(Debug, Clone, PartialEq)]
struct VectorBatchCacheKey {
    /// Per-layer fingerprint: (vertex_count, index_count).
    layers: Vec<(usize, usize)>,
    /// Camera origin quantised to avoid float drift invalidation.
    origin: [i64; 3],
}

impl VectorBatchCacheKey {
    fn new(vector_meshes: &[VectorMeshData], camera_origin: DVec3) -> Self {
        let layers: Vec<(usize, usize)> = vector_meshes
            .iter()
            .map(|m| (m.positions.len(), m.indices.len()))
            .collect();
        let origin = [
            (camera_origin.x * 100.0) as i64,
            (camera_origin.y * 100.0) as i64,
            (camera_origin.z * 100.0) as i64,
        ];
        Self { layers, origin }
    }
}

// ---------------------------------------------------------------------------
// RenderParams
// ---------------------------------------------------------------------------

/// All inputs needed for a full render frame.
///
/// Aggregated into a single struct to keep [`WgpuMapRenderer::render_full`]'s
/// signature manageable.  Lifetimes are tied to the caller's frame data.
pub struct RenderParams<'a> {
    /// Engine map state (camera, layers, terrain manager).
    pub state: &'a MapState,
    /// WGPU device for buffer/texture/bind-group creation.
    pub device: &'a wgpu::Device,
    /// WGPU queue for `write_buffer` / `write_texture` / `submit`.
    pub queue: &'a wgpu::Queue,
    /// Colour attachment view (the surface texture for this frame).
    pub color_view: &'a wgpu::TextureView,
    /// Visible tile set for this frame (from engine's tile manager).
    pub visible_tiles: &'a [VisibleTile],
    /// Tessellated vector meshes to render (one per visible vector layer).
    pub vector_meshes: &'a [VectorMeshData],
    /// 3D model instances to render.
    pub model_instances: &'a [ModelInstance],
    /// Background / clear colour `[r, g, b, a]` in linear sRGB.
    ///
    /// Also used as the fog horizon colour.  Defaults to white if not set.
    pub clear_color: [f32; 4],
}

// ---------------------------------------------------------------------------
// WgpuMapRenderer
// ---------------------------------------------------------------------------

/// The WGPU-based map renderer.
///
/// Owns all persistent GPU resources (pipelines, uniform buffer, atlas,
/// sampler, depth texture) and provides [`render`](Self::render) /
/// [`render_full`](Self::render_full) to draw one frame.
///
/// See the [module-level documentation](self) for the full resource
/// layout and frame lifecycle.
///
/// ## Construction
///
/// ```ignore
/// let renderer = WgpuMapRenderer::new(&device, &queue, surface_format, width, height);
/// ```
///
/// ## Resize
///
/// Call [`resize`](Self::resize) whenever the surface dimensions change.
/// This recreates the depth texture.  Passing `width=0` or `height=0` is
/// clamped to 1x1 to avoid WGPU validation errors.
///
/// ## GPU batching
///
/// Tile textures are packed into shared 4096x4096 atlas pages
/// ([`TileAtlas`]).  All tiles on the same page are drawn in a single
/// batched draw call, reducing draw calls from N (one per tile) to P
/// (one per atlas page, typically 1-2).  Terrain meshes are batched
/// identically.  Vector layers are one draw call each.  Model mesh
/// GPU buffers are cached by identity fingerprint across frames.
pub struct WgpuMapRenderer {
    // -- Pipelines --------------------------------------------------------
    tile_pipeline: TilePipeline,
    terrain_pipeline: TerrainPipeline,
    terrain_data_pipeline: TerrainDataPipeline,
    hillshade_pipeline: HillshadePipeline,
    grid_scalar_pipeline: GridScalarPipeline,
    grid_extrusion_pipeline: GridExtrusionPipeline,
    column_pipeline: ColumnPipeline,
    vector_pipeline: VectorPipeline,
    fill_pipeline: FillPipeline,
    fill_pattern_pipeline: FillPatternPipeline,
    fill_extrusion_pipeline: FillExtrusionPipeline,
    line_pipeline: LinePipeline,
    line_pattern_pipeline: LinePatternPipeline,
    circle_pipeline: CirclePipeline,
    heatmap_pipeline: HeatmapPipeline,
    /// Heatmap colour-mapping pipeline (Pass 2: fullscreen ramp composite).
    heatmap_colormap_pipeline: HeatmapColormapPipeline,
    symbol_pipeline: SymbolPipeline,
    model_pipeline: ModelPipeline,
    image_overlay_pipeline: ImageOverlayPipeline,

    // -- Shared uniform ---------------------------------------------------
    /// A single 64-byte uniform buffer holding the view-projection matrix.
    /// Shared by all four pipelines (each has its own bind group pointing
    /// to this buffer).
    uniform_buffer: wgpu::Buffer,
    /// Tile pipeline's uniform bind group (group 0).
    uniform_bind_group: wgpu::BindGroup,
    /// Terrain pipeline's uniform bind group (group 0).
    terrain_uniform_bind_group: wgpu::BindGroup,
    /// Terrain data pipeline's uniform bind group (group 0).
    terrain_data_uniform_bind_group: wgpu::BindGroup,
    /// Hillshade pipeline's uniform bind group (group 0).
    hillshade_uniform_bind_group: wgpu::BindGroup,
    /// Grid scalar pipeline's uniform bind group (group 0).
    grid_scalar_uniform_bind_group: wgpu::BindGroup,
    /// Grid extrusion pipeline's uniform bind group (group 0).
    grid_extrusion_uniform_bind_group: wgpu::BindGroup,
    /// Column pipeline's uniform bind group (group 0).
    column_uniform_bind_group: wgpu::BindGroup,
    /// Vector pipeline's uniform bind group (group 0).
    vector_uniform_bind_group: wgpu::BindGroup,
    /// Fill-extrusion pipeline's uniform bind group (group 0).
    fill_extrusion_uniform_bind_group: wgpu::BindGroup,
    /// Model pipeline's uniform bind group (group 0).
    model_uniform_bind_group: wgpu::BindGroup,
    /// Line pipeline's uniform bind group (group 0).
    line_uniform_bind_group: wgpu::BindGroup,
    /// Circle pipeline's uniform bind group (group 0).
    circle_uniform_bind_group: wgpu::BindGroup,
    /// Heatmap pipeline's uniform bind group (group 0).
    heatmap_uniform_bind_group: wgpu::BindGroup,
    /// Heatmap colormap pipeline's uniform bind group (group 0).
    heatmap_colormap_uniform_bind_group: wgpu::BindGroup,
    /// Off-screen R16Float accumulation texture for heatmap Pass 1.
    heatmap_accum_texture: wgpu::Texture,
    /// View into the accumulation texture.
    heatmap_accum_view: wgpu::TextureView,
    /// 256×1 Rgba8Unorm colour ramp texture for heatmap Pass 2.
    _heatmap_ramp_texture: wgpu::Texture,
    /// View into the colour ramp texture.
    heatmap_ramp_view: wgpu::TextureView,
    /// Heatmap colormap textures bind group (group 1: heat + ramp + sampler).
    heatmap_colormap_textures_bind_group: wgpu::BindGroup,
    /// Symbol pipeline's uniform bind group (group 0).
    symbol_uniform_bind_group: wgpu::BindGroup,
    /// Image overlay pipeline's uniform bind group (group 0).
    image_overlay_uniform_bind_group: wgpu::BindGroup,

    // -- Shared sampler ---------------------------------------------------
    /// Bilinear, clamp-to-edge sampler shared across all atlas page bind
    /// groups (tile + terrain).
    sampler: wgpu::Sampler,
    /// Filtering sampler for grid scalar ramp textures.
    grid_scalar_ramp_sampler: wgpu::Sampler,
    /// Repeat-mode sampler for fill-pattern textures.
    fill_pattern_sampler: wgpu::Sampler,

    // -- Depth ------------------------------------------------------------
    /// Depth texture view (`Depth32Float`), recreated on [`resize`](Self::resize).
    depth_view: wgpu::TextureView,
    /// Current surface width in pixels (? 1).
    width: u32,
    /// Current surface height in pixels (? 1).
    height: u32,
    /// Renderer-owned terrain depth / coordinate buffers.
    terrain_interaction_buffers: TerrainInteractionBuffers,

    // -- Atlas + page bind groups -----------------------------------------
    /// Tile texture atlas (persists across frames, evicted per-frame).
    tile_atlas: TileAtlas,
    /// Prepared hillshade texture atlas.
    hillshade_atlas: TileAtlas,
    /// Per-atlas-page bind groups for the **tile** pipeline (group 1: 
    /// texture view + sampler).  Rebuilt incrementally when new pages are
    /// allocated.
    page_bind_groups: Vec<wgpu::BindGroup>,
    /// Per-atlas-page bind groups for the **terrain** pipeline (group 1).
    page_terrain_bind_groups: Vec<wgpu::BindGroup>,
    /// Per-atlas-page bind groups for the **hillshade** pipeline (group 1).
    page_hillshade_bind_groups: Vec<wgpu::BindGroup>,

    // -- Model mesh cache -------------------------------------------------
    /// Cached model mesh GPU buffers keyed by [`ModelMeshKey`] fingerprint.
    /// Avoids re-uploading identical mesh geometry every frame.
    model_mesh_cache: std::collections::HashMap<ModelMeshKey, CachedModelMesh>,
    /// Shared reusable terrain grid meshes keyed by grid resolution.
    shared_terrain_grids: std::collections::HashMap<u16, SharedTerrainGridMesh>,
    /// Cached GPU elevation textures keyed by terrain tile id.
    height_texture_cache: std::collections::HashMap<TileId, CachedHeightTexture>,
    /// Shared unit-box mesh for instanced columns.
    shared_column_mesh: Option<SharedColumnMesh>,
    /// Cached per-layer grid scalar GPU state.
    grid_scalar_overlay_cache: std::collections::HashMap<LayerId, CachedGridScalarOverlay>,
    /// Cached per-layer grid extrusion GPU state.
    grid_extrusion_overlay_cache: std::collections::HashMap<LayerId, CachedGridExtrusionOverlay>,
    /// Cached per-layer instanced column GPU state.
    column_overlay_cache: std::collections::HashMap<LayerId, CachedColumnOverlay>,
    /// Cached per-layer point-cloud GPU state.
    point_cloud_overlay_cache: std::collections::HashMap<LayerId, CachedPointCloudOverlay>,

    // -- Batch buffer caches ----------------------------------------------
    /// Cached tile batch GPU buffers from the previous frame.
    cached_tile_batches: Vec<TilePageBatches>,
    /// Cache key for the current tile batch buffers.
    tile_batch_cache_key: Option<TileBatchCacheKey>,
    /// Cached vector batch GPU buffers from the previous frame.
    cached_vector_batches: Vec<Option<VectorBatchEntry>>,
    /// Cache key for the current vector batch buffers.
    vector_batch_cache_key: Option<VectorBatchCacheKey>,
    /// Cached fill-extrusion batch GPU buffers from the previous frame.
    cached_fill_extrusion_batches: Vec<Option<FillExtrusionBatchEntry>>,
    /// Cached fill batch GPU buffers from the previous frame.
    cached_fill_batches: Vec<Option<FillBatchEntry>>,
    /// Cached fill-pattern batch GPU buffers from the previous frame.
    cached_fill_pattern_batches: Vec<Option<FillPatternBatchEntry>>,
    /// Cached line batch GPU buffers from the previous frame.
    cached_line_batches: Vec<Option<LineBatchEntry>>,
    /// Cached line-pattern batch GPU buffers from the previous frame.
    cached_line_pattern_batches: Vec<Option<LinePatternBatchEntry>>,
    /// Cached circle batch GPU buffers from the previous frame.
    cached_circle_batches: Vec<Option<CircleBatchEntry>>,
    /// Cached heatmap batch GPU buffers from the previous frame.
    cached_heatmap_batches: Vec<Option<HeatmapBatchEntry>>,
    /// Cached symbol batch GPU buffers from the previous frame.
    cached_symbol_batch: Option<SymbolBatchEntry>,
    /// GPU glyph atlas texture and view for the symbol pipeline.
    symbol_atlas_texture: Option<(wgpu::Texture, wgpu::TextureView)>,
    /// Symbol atlas bind group (group 1: texture + sampler).
    symbol_atlas_bind_group: Option<wgpu::BindGroup>,
    /// Engine-side glyph atlas used for symbol rendering.
    symbol_glyph_atlas: rustial_engine::symbols::GlyphAtlas,
    /// Glyph provider for symbol rendering (font-based or procedural).
    symbol_glyph_provider: Box<dyn rustial_engine::symbols::GlyphProvider>,

    // -- Per-tile terrain bind caches -------------------------------------
    /// Cached per-tile terrain uniform buffers and bind groups.
    terrain_tile_bind_cache: std::collections::HashMap<TerrainTileBindKey, CachedTerrainTileBind>,

    // -- Terrain-data dirty tracking --------------------------------------
    /// Dirty-tracking for the terrain-data interaction pass (MapLibre's
    /// `maybeDrawDepthAndCoords` pattern).
    terrain_data_dirty: TerrainDataDirtyState,

    // -- Model transform cache --------------------------------------------
    /// Cached model instance transform buffer + bind group.
    cached_model_transforms: Option<CachedModelTransforms>,
    /// Cached placeholder quad batch from the previous frame.
    cached_placeholder_batch: Option<VectorBatchEntry>,
    /// Cached image overlay GPU resources from the previous frame.
    cached_image_overlay_batches: Vec<CachedImageOverlayBatch>,
    /// Visualization cache activity from the last render.
    visualization_perf_stats: VisualizationPerfStats,
}

/// ---------------------------------------------------------------------------
/// ModelMeshKey / CachedModelMesh
/// ---------------------------------------------------------------------------

/// Identity key for deduplicating model mesh GPU uploads.
///
/// Two meshes with the same `(pos_len, idx_len, fingerprint)` are assumed
/// identical.  The fingerprint is a cheap rolling hash of the first
/// position and first index -- sufficient for typical usage where distinct
/// meshes have different vertex counts.
///
/// **Limitation:** hash collisions are theoretically possible between two
/// meshes with identical lengths and coincidentally identical first
/// elements but different interiors.  A future improvement could hash the
/// full data or use an explicit user-provided mesh ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct ModelMeshKey {
    pos_len: usize,
    idx_len: usize,
    fingerprint: u64,
}

impl ModelMeshKey {
    fn from_mesh(mesh: &rustial_engine::ModelMesh) -> Self {
        let mut fingerprint: u64 = mesh.positions.len() as u64;
        if let Some(first) = mesh.positions.first() {
            fingerprint = fingerprint
                .wrapping_mul(31)
                .wrapping_add(first[0].to_bits() as u64)
                .wrapping_mul(31)
                .wrapping_add(first[1].to_bits() as u64)
                .wrapping_mul(31)
                .wrapping_add(first[2].to_bits() as u64);
        }
        if let Some(&first_idx) = mesh.indices.first() {
            fingerprint = fingerprint.wrapping_mul(31).wrapping_add(first_idx as u64);
        }
        Self {
            pos_len: mesh.positions.len(),
            idx_len: mesh.indices.len(),
            fingerprint,
        }
    }
}

/// A model mesh whose vertex + index buffers have been uploaded to the GPU.
struct CachedModelMesh {
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    index_count: u32,
}

/// Cached model instance transform buffer and bind group.
///
/// Avoids re-creating the GPU buffer and bind group every frame when
/// the model instance list and camera origin haven't changed.
struct CachedModelTransforms {
    #[allow(dead_code)]
    buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    /// Stride in bytes between consecutive instance transforms.
    stride: usize,
    /// Instance count at the time this was created.
    instance_count: usize,
    /// Rolling fingerprint of (instance positions + rotations + scales
    /// + camera origin).
    fingerprint: u64,
}

/// Cached GPU resources for a single image overlay.
struct CachedImageOverlayBatch {
    vertex_buffer: wgpu::Buffer,
    index_buffer: wgpu::Buffer,
    texture: wgpu::Texture,
    #[allow(dead_code)]
    texture_view: wgpu::TextureView,
    texture_bind_group: wgpu::BindGroup,
    /// Layer id that produced this overlay (for cache key matching).
    layer_id: rustial_engine::LayerId,
    /// Texture dimensions `(width, height)` for reuse checks.
    tex_dimensions: (u32, u32),
    /// Data pointer identity for fast same-frame skip.
    data_arc_ptr: usize,
}

// ---------------------------------------------------------------------------
// impl WgpuMapRenderer
// ---------------------------------------------------------------------------

impl WgpuMapRenderer {
    /// Create a new renderer.
    ///
    /// # Arguments
    ///
    /// * `device` -- WGPU device.
    /// * `_queue` -- WGPU queue (reserved for future lazy init; unused today).
    /// * `format` -- Colour target format (must match the surface's preferred format).
    /// * `width`  -- Initial surface width in pixels.
    /// * `height` -- Initial surface height in pixels.
    pub fn new(
        device: &wgpu::Device,
        _queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        width: u32,
        height: u32,
    ) -> Self {
        let tile_pipeline = TilePipeline::new(device, format);
        let terrain_pipeline =
            TerrainPipeline::new(device, format, &tile_pipeline.uniform_bind_group_layout);
        let terrain_data_pipeline = TerrainDataPipeline::new(device);
        let hillshade_pipeline = HillshadePipeline::new(device, format);
        let grid_scalar_pipeline = GridScalarPipeline::new(device, format);
        let grid_extrusion_pipeline = GridExtrusionPipeline::new(device, format);
        let column_pipeline = ColumnPipeline::new(device, format);
        let vector_pipeline = VectorPipeline::new(device, format);
        let fill_pipeline = FillPipeline::new(device, format);
        let fill_pattern_pipeline = FillPatternPipeline::new(device, format);
        let fill_extrusion_pipeline = FillExtrusionPipeline::new(device, format);
        let line_pipeline = LinePipeline::new(device, format);
        let line_pattern_pipeline = LinePatternPipeline::new(device, format);
        let circle_pipeline = CirclePipeline::new(device, format);
        let heatmap_pipeline = HeatmapPipeline::new(device);
        let heatmap_colormap_pipeline = HeatmapColormapPipeline::new(device, format);
        let symbol_pipeline = SymbolPipeline::new(device, format);
        let model_pipeline = ModelPipeline::new(device, format);
        let image_overlay_pipeline = ImageOverlayPipeline::new(device, format);

        // Shared uniform buffer (view-projection + fog parameters).
        let uniform_data = ViewProjUniform::from_dmat4(&glam::DMat4::IDENTITY);
        let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("rustial_uniform_buf"),
            contents: bytemuck::bytes_of(&uniform_data),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        });

        // Four bind groups pointing to the same buffer -- one per pipeline.
        // Each pipeline may have a different `BindGroupLayout` (even though
        // the layout *happens* to be identical today) so we create separate
        // bind groups to stay correct if layouts diverge.
        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_uniform_bg"),
            layout: &tile_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let column_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_column_uniform_bg"),
            layout: &column_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let grid_extrusion_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_grid_extrusion_uniform_bg"),
            layout: &grid_extrusion_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let terrain_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_terrain_uniform_bg"),
            layout: &terrain_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let hillshade_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_hillshade_uniform_bg"),
            layout: &hillshade_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let grid_scalar_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_grid_scalar_uniform_bg"),
            layout: &grid_scalar_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let vector_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_vector_uniform_bg"),
            layout: &vector_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let fill_extrusion_uniform_bind_group =
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("rustial_fill_extrusion_uniform_bg"),
                layout: &fill_extrusion_pipeline.uniform_bind_group_layout,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform_buffer.as_entire_binding(),
                }],
            });

        let model_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_model_uniform_bg"),
            layout: &model_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let line_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_line_uniform_bg"),
            layout: &line_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let circle_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_circle_uniform_bg"),
            layout: &circle_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let heatmap_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_heatmap_uniform_bg"),
            layout: &heatmap_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let heatmap_colormap_uniform_bind_group =
            device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("rustial_heatmap_colormap_uniform_bg"),
                layout: &heatmap_colormap_pipeline.uniform_bind_group_layout,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform_buffer.as_entire_binding(),
                }],
            });

        let symbol_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_symbol_uniform_bg"),
            layout: &symbol_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let image_overlay_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_image_overlay_uniform_bg"),
            layout: &image_overlay_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let terrain_data_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rustial_terrain_data_uniform_bg"),
            layout: &terrain_data_pipeline.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("rustial_sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Linear,
            anisotropy_clamp: 16,
            ..Default::default()
        });

        let grid_scalar_ramp_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("rustial_grid_scalar_ramp_sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        let fill_pattern_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("rustial_fill_pattern_sampler"),
            address_mode_u: wgpu::AddressMode::Repeat,
            address_mode_v: wgpu::AddressMode::Repeat,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });

        // Clamp to at least 1x1 so the depth texture is always valid.
        let w = width.max(1);
        let h = height.max(1);
        let depth_view = create_depth_texture(device, w, h);
        let terrain_interaction_buffers = TerrainInteractionBuffers::new(device, w, h);

        // -- Heatmap off-screen resources ---------------------------------
        let (heatmap_accum_texture, heatmap_accum_view) =
            create_heatmap_accum_texture(device, w, h);
        let heatmap_ramp_texture = create_default_heatmap_ramp_texture(device, _queue);
        let heatmap_ramp_view =
            heatmap_ramp_texture.create_view(&wgpu::TextureViewDescriptor::default());
        let heatmap_colormap_textures_bind_group =
            create_heatmap_colormap_bind_group(
                device,
                &heatmap_colormap_pipeline.textures_bind_group_layout,
                &heatmap_accum_view,
                &heatmap_ramp_view,
                &sampler,
            );

        Self {
            tile_pipeline,
            terrain_pipeline,
            terrain_data_pipeline,
            hillshade_pipeline,
            grid_scalar_pipeline,
            grid_extrusion_pipeline,
            column_pipeline,
            vector_pipeline,
            fill_pipeline,
            fill_pattern_pipeline,
            fill_extrusion_pipeline,
            line_pipeline,
            line_pattern_pipeline,
            circle_pipeline,
            heatmap_pipeline,
            heatmap_colormap_pipeline,
            symbol_pipeline,
            model_pipeline,
            image_overlay_pipeline,
            uniform_buffer,
            uniform_bind_group,
            terrain_uniform_bind_group,
            terrain_data_uniform_bind_group,
            hillshade_uniform_bind_group,
            grid_scalar_uniform_bind_group,
            grid_extrusion_uniform_bind_group,
            column_uniform_bind_group,
            vector_uniform_bind_group,
            fill_extrusion_uniform_bind_group,
            model_uniform_bind_group,
            line_uniform_bind_group,
            circle_uniform_bind_group,
            heatmap_uniform_bind_group,
            heatmap_colormap_uniform_bind_group,
            heatmap_accum_texture,
            heatmap_accum_view,
            _heatmap_ramp_texture: heatmap_ramp_texture,
            heatmap_ramp_view,
            heatmap_colormap_textures_bind_group,
            symbol_uniform_bind_group,
            image_overlay_uniform_bind_group,
            sampler,
            grid_scalar_ramp_sampler,
            fill_pattern_sampler,
            depth_view,
            width: w,
            height: h,
            terrain_interaction_buffers,
            tile_atlas: TileAtlas::new(),
            hillshade_atlas: TileAtlas::new(),
            page_bind_groups: Vec::new(),
            page_terrain_bind_groups: Vec::new(),
            page_hillshade_bind_groups: Vec::new(),
            model_mesh_cache: std::collections::HashMap::new(),
            shared_terrain_grids: std::collections::HashMap::new(),
            height_texture_cache: std::collections::HashMap::new(),
            shared_column_mesh: None,
            grid_scalar_overlay_cache: std::collections::HashMap::new(),
            grid_extrusion_overlay_cache: std::collections::HashMap::new(),
            column_overlay_cache: std::collections::HashMap::new(),
            point_cloud_overlay_cache: std::collections::HashMap::new(),
            cached_tile_batches: Vec::new(),
            tile_batch_cache_key: None,
            cached_vector_batches: Vec::new(),
            vector_batch_cache_key: None,
            cached_fill_extrusion_batches: Vec::new(),
            cached_fill_batches: Vec::new(),
            cached_fill_pattern_batches: Vec::new(),
            cached_line_batches: Vec::new(),
            cached_line_pattern_batches: Vec::new(),
            cached_circle_batches: Vec::new(),
            cached_heatmap_batches: Vec::new(),
            cached_symbol_batch: None,
            symbol_atlas_texture: None,
            symbol_atlas_bind_group: None,
            symbol_glyph_atlas: rustial_engine::symbols::GlyphAtlas::new(),
            symbol_glyph_provider: Box::new(rustial_engine::symbols::ProceduralGlyphProvider::new()),
            terrain_tile_bind_cache: std::collections::HashMap::new(),
            terrain_data_dirty: TerrainDataDirtyState::default(),
            cached_model_transforms: None,
            cached_placeholder_batch: None,
            cached_image_overlay_batches: Vec::new(),
            visualization_perf_stats: VisualizationPerfStats::default(),
        }
    }

    // -- Surface management -----------------------------------------------

    /// Notify the renderer that the surface was resized.
    ///
    /// Recreates the depth texture.  Dimensions are clamped to at least
    /// 1x1 -- passing `0` is safe and produces a 1-pixel texture.
    pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) {
        self.width = width.max(1);
        self.height = height.max(1);
        self.depth_view = create_depth_texture(device, self.width, self.height);
        self.terrain_interaction_buffers.resize(device, self.width, self.height);
        self.terrain_data_dirty.dirty = true;

        // Recreate heatmap accumulation texture at new size and rebuild the
        // colour-map bind group that references it.
        let (tex, view) = create_heatmap_accum_texture(device, self.width, self.height);
        self.heatmap_accum_texture = tex;
        self.heatmap_accum_view = view;
        self.heatmap_colormap_textures_bind_group = create_heatmap_colormap_bind_group(
            device,
            &self.heatmap_colormap_pipeline.textures_bind_group_layout,
            &self.heatmap_accum_view,
            &self.heatmap_ramp_view,
            &self.sampler,
        );
    }

    /// Replace the glyph provider used for symbol text rendering.
    ///
    /// By default the renderer uses [`ProceduralGlyphProvider`] which
    /// produces placeholder glyphs.  Pass a
    /// [`ShapedGlyphProvider`](rustial_engine::symbols::text_shaper::ShapedGlyphProvider)
    /// (when the `text-shaping` feature is enabled) to render real
    /// font-based SDF text.
    pub fn set_glyph_provider(
        &mut self,
        provider: Box<dyn rustial_engine::symbols::GlyphProvider>,
    ) {
        self.symbol_glyph_provider = provider;
    }

    // -- Tile upload ------------------------------------------------------

    /// Enqueue a decoded tile image for deferred GPU upload.
    ///
    /// If the tile is already present this is a no-op.  Otherwise the slot
    /// is allocated and a deferred upload is enqueued.  The actual GPU
    /// `write_texture` happens when [`flush_atlas_uploads`] is called
    /// during the frame.  Page bind groups are rebuilt if a new atlas page
    /// was created.
    pub fn upload_tile(
        &mut self,
        device: &wgpu::Device,
        tile_id: TileId,
        image: &DecodedImage,
    ) {
        if self.tile_atlas.contains(&tile_id) {
            return;
        }

        if let Err(err) = image.validate_rgba8() {
            log::warn!("wgpu upload_tile: skipping invalid tile {:?}: {}", tile_id, err);
            return;
        }

        self.tile_atlas.insert(device, tile_id, image);
        self.tile_batch_cache_key = None;

        // Rebuild page bind groups if new pages were created.
        self.rebuild_page_bind_groups(device);
    }

    /// Enqueue a prepared hillshade texture for deferred GPU upload.
    pub fn upload_hillshade(
        &mut self,
        device: &wgpu::Device,
        tile_id: TileId,
        image: &DecodedImage,
    ) {
        if self.hillshade_atlas.contains(&tile_id) {
            return;
        }
        if let Err(err) = image.validate_rgba8() {
            log::warn!("wgpu upload_hillshade: skipping invalid tile {:?}: {}", tile_id, err);
            return;
        }
        self.hillshade_atlas.insert(device, tile_id, image);
        self.rebuild_page_bind_groups(device);
    }

    /// Flush all pending atlas texture uploads to the GPU.
    ///
    /// Writes only the affected slot pixel rectangles (partial writes)
    /// rather than re-uploading full atlas pages.  Call once per frame
    /// after all [`upload_tile`](Self::upload_tile) /
    /// [`upload_hillshade`](Self::upload_hillshade) calls and before
    /// building batched geometry.
    pub fn flush_atlas_uploads(&mut self, queue: &wgpu::Queue) {
        self.tile_atlas.flush_uploads(queue);
        self.hillshade_atlas.flush_uploads(queue);
    }

    fn get_or_create_shared_column_mesh(&mut self, device: &wgpu::Device) -> &SharedColumnMesh {
        if self.shared_column_mesh.is_none() {
            let (vertices, indices) = build_unit_column_mesh();
            let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("column_unit_box_vb"),
                contents: bytemuck::cast_slice(&vertices),
                usage: wgpu::BufferUsages::VERTEX,
            });
            let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("column_unit_box_ib"),
                contents: bytemuck::cast_slice(&indices),
                usage: wgpu::BufferUsages::INDEX,
            });
            self.shared_column_mesh = Some(SharedColumnMesh {
                vertex_buffer,
                index_buffer,
                index_count: indices.len() as u32,
            });
        }
        self.shared_column_mesh.as_ref().expect("column mesh")
    }

    fn get_or_create_grid_scalar_overlay(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        overlay: &VisualizationOverlay,
        state: &MapState,
        scene_origin: DVec3,
        terrain_fingerprint: u64,
    ) -> Option<()> {
        let VisualizationOverlay::GridScalar { layer_id, grid, field, ramp } = overlay else {
            return None;
        };

        let origin_key = [
            (scene_origin.x * 100.0) as i64,
            (scene_origin.y * 100.0) as i64,
            (scene_origin.z * 100.0) as i64,
        ];
        let ramp_fingerprint = grid_scalar_ramp_fingerprint(ramp);
        let grid_fingerprint = grid_extrusion_grid_fingerprint(grid);
        let projection = state.camera().projection();
        let (vertices, indices) = build_grid_scalar_geometry(grid, state, scene_origin);

        let recreate = if let Some(cached) = self.grid_scalar_overlay_cache.get(layer_id) {
            cached.generation != field.generation
                || cached.ramp_fingerprint != ramp_fingerprint
                || cached.grid_fingerprint != grid_fingerprint
                || cached.projection != projection
                || cached.index_count as usize != indices.len()
                || cached.vertex_count != vertices.len()
        } else {
            true
        };

        if recreate {
            self.visualization_perf_stats.grid_scalar_rebuilds += 1;
            let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("grid_scalar_vb_{layer_id}")),
                contents: bytemuck::cast_slice(&vertices),
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            });
            let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("grid_scalar_ib_{layer_id}")),
                contents: bytemuck::cast_slice(&indices),
                usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
            });
            let scalar_texture = create_grid_scalar_texture(device, queue, field);
            let scalar_view = scalar_texture.create_view(&wgpu::TextureViewDescriptor::default());
            let ramp_texture = create_grid_scalar_ramp_texture(device, queue, ramp);
            let ramp_view = ramp_texture.create_view(&wgpu::TextureViewDescriptor::default());
            let uniform = build_grid_scalar_uniform(grid, field, state, scene_origin, 1.0);
            let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("grid_scalar_uniform_{layer_id}")),
                contents: bytemuck::bytes_of(&uniform),
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            });
            let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(&format!("grid_scalar_bg_{layer_id}")),
                layout: &self.grid_scalar_pipeline.overlay_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: uniform_buffer.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::TextureView(&scalar_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::TextureView(&ramp_view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 3,
                        resource: wgpu::BindingResource::Sampler(&self.grid_scalar_ramp_sampler),
                    },
                ],
            });
            self.grid_scalar_overlay_cache.insert(
                *layer_id,
                CachedGridScalarOverlay {
                    vertex_buffer,
                    index_buffer,
                    index_count: indices.len() as u32,
                    vertex_count: vertices.len(),
                    uniform_buffer,
                    bind_group,
                    scalar_texture,
                    ramp_texture,
                    generation: field.generation,
                    value_generation: field.value_generation,
                    ramp_fingerprint,
                    grid_fingerprint,
                    terrain_fingerprint,
                    projection,
                    origin_key,
                },
            );
            return Some(());
        }

        if let Some(cached) = self.grid_scalar_overlay_cache.get_mut(layer_id) {
            let uniform = build_grid_scalar_uniform(grid, field, state, scene_origin, 1.0);
            if cached.value_generation != field.value_generation {
                self.visualization_perf_stats.grid_scalar_value_updates += 1;
                write_grid_scalar_texture(queue, &cached.scalar_texture, field);
                cached.value_generation = field.value_generation;
                queue.write_buffer(&cached.uniform_buffer, 0, bytemuck::bytes_of(&uniform));
            }
            if cached.origin_key != origin_key || cached.terrain_fingerprint != terrain_fingerprint {
                queue.write_buffer(
                    &cached.vertex_buffer,
                    0,
                    bytemuck::cast_slice::<GridScalarVertex, u8>(&vertices),
                );
                queue.write_buffer(&cached.uniform_buffer, 0, bytemuck::bytes_of(&uniform));
                cached.origin_key = origin_key;
                cached.terrain_fingerprint = terrain_fingerprint;
            }
        }

        Some(())
    }

    fn get_or_create_point_cloud_overlay(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        overlay: &VisualizationOverlay,
        state: &MapState,
        scene_origin: DVec3,
    ) -> Option<()> {
        let VisualizationOverlay::Points { layer_id, points, ramp } = overlay else {
            return None;
        };

        let origin_key = [
            (scene_origin.x * 100.0) as i64,
            (scene_origin.y * 100.0) as i64,
            (scene_origin.z * 100.0) as i64,
        ];
        let points_fingerprint = point_set_fingerprint(points);
        let ramp_fingerprint = grid_scalar_ramp_fingerprint(ramp);
        let instances = build_point_instances(points, ramp, state, scene_origin);

        let needs_rebuild = if let Some(cached) = self.point_cloud_overlay_cache.get(layer_id) {
            cached.generation != points.generation
                || cached.ramp_fingerprint != ramp_fingerprint
                || cached.instance_count as usize != instances.len()
        } else {
            true
        };

        if needs_rebuild {
            self.visualization_perf_stats.point_cloud_rebuilds += 1;
            let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("point_cloud_instances_{layer_id}")),
                contents: bytemuck::cast_slice(&instances),
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            });
            self.point_cloud_overlay_cache.insert(
                *layer_id,
                CachedPointCloudOverlay {
                    instance_buffer,
                    instance_count: instances.len() as u32,
                    generation: points.generation,
                    origin_key,
                    points_fingerprint,
                    ramp_fingerprint,
                    instance_data: instances,
                },
            );
            return Some(());
        }

        if let Some(cached) = self.point_cloud_overlay_cache.get_mut(layer_id) {
            let ranges = diff_column_instance_ranges(&cached.instance_data, &instances);
            if !ranges.is_empty() {
                self.visualization_perf_stats.point_cloud_partial_writes += 1;
                self.visualization_perf_stats.point_cloud_partial_write_ranges += ranges.len() as u32;
            }
            for range in ranges {
                let start = range.start;
                let end = range.end;
                let byte_offset =
                    (start * std::mem::size_of::<ColumnInstanceData>()) as wgpu::BufferAddress;
                queue.write_buffer(
                    &cached.instance_buffer,
                    byte_offset,
                    bytemuck::cast_slice::<ColumnInstanceData, u8>(&instances[start..end]),
                );
            }
            cached.instance_data = instances;
            cached.origin_key = origin_key;
            cached.points_fingerprint = points_fingerprint;
        }

        Some(())
    }

    fn get_or_create_grid_extrusion_overlay(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        overlay: &VisualizationOverlay,
        state: &MapState,
        scene_origin: DVec3,
        terrain_fingerprint: u64,
    ) -> Option<()> {
        let VisualizationOverlay::GridExtrusion {
            layer_id,
            grid,
            field,
            ramp,
            params,
        } = overlay else {
            return None;
        };

        let origin_key = [
            (scene_origin.x * 100.0) as i64,
            (scene_origin.y * 100.0) as i64,
            (scene_origin.z * 100.0) as i64,
        ];
        let grid_fingerprint = grid_extrusion_grid_fingerprint(grid);
        let params_fingerprint = grid_extrusion_params_fingerprint(params);
        let ramp_fingerprint = grid_scalar_ramp_fingerprint(ramp);

        let (vertices, indices) = build_grid_extrusion_geometry(grid, field, ramp, params, state, scene_origin);

        let needs_rebuild = if let Some(cached) = self.grid_extrusion_overlay_cache.get(layer_id) {
            cached.generation != field.generation
                || cached.grid_fingerprint != grid_fingerprint
                || cached.params_fingerprint != params_fingerprint
                || cached.ramp_fingerprint != ramp_fingerprint
                || cached.terrain_fingerprint != terrain_fingerprint
                || cached.index_count as usize != indices.len()
                || cached.vertex_count != vertices.len()
        } else {
            true
        };

        if needs_rebuild {
            self.visualization_perf_stats.grid_extrusion_rebuilds += 1;
            let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("grid_extrusion_vb_{layer_id}")),
                contents: bytemuck::cast_slice(&vertices),
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            });
            let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("grid_extrusion_ib_{layer_id}")),
                contents: bytemuck::cast_slice(&indices),
                usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
            });

            self.grid_extrusion_overlay_cache.insert(
                *layer_id,
                CachedGridExtrusionOverlay {
                    vertex_buffer,
                    index_buffer,
                    index_count: indices.len() as u32,
                    vertex_count: vertices.len(),
                    generation: field.generation,
                    value_generation: field.value_generation,
                    origin_key,
                    grid_fingerprint,
                    params_fingerprint,
                    ramp_fingerprint,
                    terrain_fingerprint,
                },
            );
            return Some(());
        }

        if let Some(cached) = self.grid_extrusion_overlay_cache.get_mut(layer_id) {
            if cached.value_generation != field.value_generation || cached.origin_key != origin_key {
                self.visualization_perf_stats.grid_extrusion_value_updates += 1;
                let vertex_bytes = bytemuck::cast_slice::<GridExtrusionVertex, u8>(&vertices);
                queue.write_buffer(&cached.vertex_buffer, 0, vertex_bytes);
            }
            cached.value_generation = field.value_generation;
            cached.origin_key = origin_key;
            cached.terrain_fingerprint = terrain_fingerprint;
        }
        Some(())
    }

    fn get_or_create_column_overlay(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        overlay: &VisualizationOverlay,
        state: &MapState,
        scene_origin: DVec3,
    ) -> Option<()> {
        let VisualizationOverlay::Columns { layer_id, columns, ramp } = overlay else {
            return None;
        };

        let origin_key = [
            (scene_origin.x * 100.0) as i64,
            (scene_origin.y * 100.0) as i64,
            (scene_origin.z * 100.0) as i64,
        ];
        let columns_fingerprint = column_set_fingerprint(columns);
        let ramp_fingerprint = grid_scalar_ramp_fingerprint(ramp);
        let instances = build_column_instances(columns, ramp, state, scene_origin);

        let needs_rebuild = if let Some(cached) = self.column_overlay_cache.get(layer_id) {
            cached.generation != columns.generation
                || cached.ramp_fingerprint != ramp_fingerprint
                || cached.instance_count as usize != instances.len()
        } else {
            true
        };

        if needs_rebuild {
            self.visualization_perf_stats.column_rebuilds += 1;
            let instance_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("column_instances_{layer_id}")),
                contents: bytemuck::cast_slice(&instances),
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            });
            self.column_overlay_cache.insert(
                *layer_id,
                CachedColumnOverlay {
                    instance_buffer,
                    instance_count: instances.len() as u32,
                    generation: columns.generation,
                    origin_key,
                    columns_fingerprint,
                    ramp_fingerprint,
                    instance_data: instances,
                },
            );
            return Some(());
        }

        if let Some(cached) = self.column_overlay_cache.get_mut(layer_id) {
            let ranges = diff_column_instance_ranges(&cached.instance_data, &instances);
            if !ranges.is_empty() {
                self.visualization_perf_stats.column_partial_writes += 1;
                self.visualization_perf_stats.column_partial_write_ranges += ranges.len() as u32;
            }
            for range in ranges {
                let start = range.start;
                let end = range.end;
                let byte_offset =
                    (start * std::mem::size_of::<ColumnInstanceData>()) as wgpu::BufferAddress;
                queue.write_buffer(
                    &cached.instance_buffer,
                    byte_offset,
                    bytemuck::cast_slice::<ColumnInstanceData, u8>(&instances[start..end]),
                );
            }
            cached.instance_data = instances;
            cached.origin_key = origin_key;
            cached.columns_fingerprint = columns_fingerprint;
        }

        Some(())
    }

    // -- Render entry points ----------------------------------------------

    /// Render one frame of the map (tiles only, no vectors or models).
    ///
    /// Convenience wrapper around [`render_full`](Self::render_full) that
    /// passes empty slices for `vector_meshes` and `model_instances`.
    pub fn render(
        &mut self,
        state: &MapState,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        color_view: &wgpu::TextureView,
        visible_tiles: &[VisibleTile],
    ) {
        let clear_color = state.computed_fog().clear_color;
         self.render_full(&RenderParams {
             state,
             device,
             queue,
             color_view,
             visible_tiles,
             vector_meshes: &[],
             model_instances: &[],
             clear_color,
         });
     }

    /// Render one full frame: tiles (or terrain), vectors, and models.
    ///
    /// See the [module-level frame lifecycle](self) for the step-by-step
    /// breakdown.
    ///
    /// ## Batching strategy
    ///
    /// 1. **Tiles / terrain** -- all quads / meshes sharing the same atlas
    ///    page are merged into a single vertex + index buffer and drawn
    ///    with one `draw_indexed` call per page.
    /// 2. **Vectors** -- each vector layer produces one draw call (already
    ///    pre-merged by the engine tessellator).
    /// 3. **Models** -- mesh GPU buffers are cached by identity fingerprint;
    ///    per-instance transform uniform + bind group are allocated
    ///    per-frame (future: dynamic UBO).
    pub fn render_full(&mut self, params: &RenderParams<'_>) {
        self.visualization_perf_stats = VisualizationPerfStats::default();
         // ?? 1. Camera-relative view-projection ??????????????????????????
        let scene_camera_origin = params.state.scene_world_origin();
        let frame = params.state.frame_output();
        let visualization = &frame.visualization;
         let view = params.state.camera().view_matrix(DVec3::ZERO);
         let proj = params.state.camera().projection_matrix();
         let vp = proj * view;

        // Fog: read pre-computed fog from the engine (centralised,
        // replaces the duplicated fog math that was previously inline here).
        let cam = params.state.camera();
        let eye = cam.eye_offset();
        let fog = params.state.computed_fog();
        let clear_color = fog.clear_color;

        let mut uniform = ViewProjUniform::from_dmat4(&vp);
        uniform.fog_color = fog.fog_color;
        uniform.eye_pos = [eye.x as f32, eye.y as f32, eye.z as f32, 0.0];
        uniform.fog_params = [fog.fog_start, fog.fog_end, fog.fog_density, 0.0];
        if let Some(hillshade) = params.state.hillshade() {
            uniform.hillshade_highlight = hillshade.highlight_color;
            uniform.hillshade_shadow = hillshade.shadow_color;
            uniform.hillshade_accent = hillshade.accent_color;
            uniform.hillshade_light = [
                hillshade.illumination_direction,
                hillshade.illumination_altitude,
                hillshade.exaggeration,
                hillshade.opacity,
            ];
        }

        params
            .queue
            .write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniform));

        // ?? 2. Enqueue new tile textures into the atlas ??????????????????
        for vt in params.visible_tiles {
            if let Some(TileData::Raster(ref img)) = vt.data {
                self.upload_tile(params.device, vt.actual, img);
            }
        }
        for raster in params.state.hillshade_rasters() {
            self.upload_hillshade(params.device, raster.tile, &raster.image);
        }

        // ?? 2b. Flush deferred atlas uploads (partial texture writes) ??
        self.flush_atlas_uploads(params.queue);

        // ?? 3. Mark visible + terrain tiles as used (prevents eviction) ?
        for vt in params.visible_tiles {
            self.tile_atlas.mark_used(&vt.actual);
        }
        let terrain_meshes = params.state.terrain_meshes();
        for mesh in terrain_meshes {
            if let Some(actual_tile) = find_terrain_texture_actual(mesh.tile, params.visible_tiles) {
                self.tile_atlas.mark_used(&actual_tile);
            }
        }
        for raster in params.state.hillshade_rasters() {
            self.hillshade_atlas.mark_used(&raster.tile);
        }

        let use_shared_terrain = !terrain_meshes.is_empty()
            && matches!(
                params.state.camera().projection(),
                rustial_engine::CameraProjection::WebMercator
                    | rustial_engine::CameraProjection::Equirectangular
            )
            && terrain_meshes.iter().all(|mesh| mesh.elevation_texture.is_some());

        let materialized_terrain_meshes: Vec<TerrainMeshData> = if use_shared_terrain {
            Vec::new()
        } else {
            terrain_meshes
                .iter()
                .map(|mesh| {
                    materialize_terrain_mesh(
                        mesh,
                        params.state.camera().projection(),
                        rustial_engine::skirt_height(
                            mesh.tile.zoom,
                            mesh.vertical_exaggeration as f64,
                        ),
                    )
                })
                .collect()
        };

        // ?? 4. Cache model mesh GPU buffers ?????????????????????????????
        if !params.model_instances.is_empty() {
            self.cache_model_meshes(params.device, params.model_instances);
            self.cache_model_transforms(
                params.device,
                params.model_instances,
                scene_camera_origin,
                params.state,
            );
        } else {
            self.cached_model_transforms = None;
        }

        // ?? 5. Build batched geometry (tiles, terrain, vectors) ??????
        let tile_batch_key = TileBatchCacheKey::new(
            params.visible_tiles,
            scene_camera_origin,
            params.state.camera().projection(),
        );
        if self.tile_batch_cache_key.as_ref() != Some(&tile_batch_key) {
            self.cached_tile_batches = build_tile_batches(
                params.device,
                params.visible_tiles,
                &self.tile_atlas,
                scene_camera_origin,
                params.state.camera().projection(),
            );
            self.tile_batch_cache_key = Some(tile_batch_key);
        }

        let terrain_batches = if !use_shared_terrain && !materialized_terrain_meshes.is_empty() {
            build_terrain_batches(
                params.device,
                &materialized_terrain_meshes,
                &self.tile_atlas,
                scene_camera_origin,
                params.visible_tiles,
            )
        } else {
            Vec::new()
        };

        let hillshade_batches = if !materialized_terrain_meshes.is_empty() && !params.state.hillshade_rasters().is_empty() {
            build_hillshade_batches(
                params.device,
                &materialized_terrain_meshes,
                params.state.hillshade_rasters(),
                &self.hillshade_atlas,
                scene_camera_origin,
            )
        } else {
            Vec::new()
        };

        let vector_batch_key = VectorBatchCacheKey::new(params.vector_meshes, scene_camera_origin);
        if self.vector_batch_cache_key.as_ref() != Some(&vector_batch_key) {
            self.cached_vector_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::Generic)
                .map(|mesh| build_vector_batch(params.device, mesh, scene_camera_origin))
                .collect();
            self.cached_fill_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::Fill && mesh.fill_pattern.is_none())
                .map(|mesh| build_fill_batch(
                    params.device,
                    mesh,
                    scene_camera_origin,
                    &self.uniform_buffer,
                    &self.fill_pipeline.uniform_bind_group_layout,
                ))
                .collect();
            self.cached_fill_pattern_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::Fill && mesh.fill_pattern.is_some())
                .map(|mesh| build_fill_pattern_batch(
                    params.device,
                    params.queue,
                    mesh,
                    scene_camera_origin,
                    &self.uniform_buffer,
                    &self.fill_pattern_pipeline.uniform_bind_group_layout,
                    &self.fill_pattern_pipeline.texture_bind_group_layout,
                    &self.fill_pattern_sampler,
                ))
                .collect();
            self.cached_fill_extrusion_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::FillExtrusion)
                .map(|mesh| build_fill_extrusion_batch(params.device, mesh, scene_camera_origin))
                .collect();
            self.cached_line_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::Line && mesh.line_pattern.is_none())
                .map(|mesh| build_line_batch(params.device, mesh, scene_camera_origin))
                .collect();
            self.cached_line_pattern_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::Line && mesh.line_pattern.is_some())
                .map(|mesh| build_line_pattern_batch(
                    params.device,
                    params.queue,
                    mesh,
                    scene_camera_origin,
                    &self.uniform_buffer,
                    &self.line_pattern_pipeline.uniform_bind_group_layout,
                    &self.line_pattern_pipeline.texture_bind_group_layout,
                    &self.fill_pattern_sampler,
                ))
                .collect();
            self.cached_circle_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::Circle)
                .map(|mesh| build_circle_batch(params.device, mesh, scene_camera_origin))
                .collect();
            self.cached_heatmap_batches = params
                .vector_meshes
                .iter()
                .filter(|mesh| mesh.render_mode == VectorRenderMode::Heatmap)
                .map(|mesh| build_heatmap_batch(params.device, mesh, scene_camera_origin))
                .collect();
            self.vector_batch_cache_key = Some(vector_batch_key);
        }

        // Build symbol batch from placed symbols.
        {
            let symbols = &frame.symbols;
            if !symbols.is_empty() {
                // Request glyphs for all visible symbols.
                self.symbol_glyph_atlas = rustial_engine::symbols::GlyphAtlas::new();
                for symbol in symbols.iter() {
                    if symbol.visible && symbol.opacity > 0.0 {
                        if let Some(text) = &symbol.text {
                            self.symbol_glyph_atlas.request_text(&symbol.font_stack, text);
                        }
                    }
                }
                // Rasterize requested glyphs.
                self.symbol_glyph_atlas.load_requested(&*self.symbol_glyph_provider);

                let dims = self.symbol_glyph_atlas.dimensions();
                if dims[0] > 0 && dims[1] > 0 {
                    // Upload atlas texture.
                    let tex = params.device.create_texture(&wgpu::TextureDescriptor {
                        label: Some("symbol_atlas_tex"),
                        size: wgpu::Extent3d {
                            width: dims[0] as u32,
                            height: dims[1] as u32,
                            depth_or_array_layers: 1,
                        },
                        mip_level_count: 1,
                        sample_count: 1,
                        dimension: wgpu::TextureDimension::D2,
                        format: wgpu::TextureFormat::R8Unorm,
                        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                        view_formats: &[],
                    });
                    params.queue.write_texture(
                        wgpu::TexelCopyTextureInfo {
                            texture: &tex,
                            mip_level: 0,
                            origin: wgpu::Origin3d::ZERO,
                            aspect: wgpu::TextureAspect::All,
                        },
                        self.symbol_glyph_atlas.alpha(),
                        wgpu::TexelCopyBufferLayout {
                            offset: 0,
                            bytes_per_row: Some(dims[0] as u32),
                            rows_per_image: Some(dims[1] as u32),
                        },
                        wgpu::Extent3d {
                            width: dims[0] as u32,
                            height: dims[1] as u32,
                            depth_or_array_layers: 1,
                        },
                    );
                    let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
                    let atlas_bg = params.device.create_bind_group(&wgpu::BindGroupDescriptor {
                        label: Some("symbol_atlas_bg"),
                        layout: &self.symbol_pipeline.atlas_bind_group_layout,
                        entries: &[
                            wgpu::BindGroupEntry {
                                binding: 0,
                                resource: wgpu::BindingResource::TextureView(&view),
                            },
                            wgpu::BindGroupEntry {
                                binding: 1,
                                resource: wgpu::BindingResource::Sampler(&self.sampler),
                            },
                        ],
                    });
                    self.symbol_atlas_texture = Some((tex, view));
                    self.symbol_atlas_bind_group = Some(atlas_bg);
                }

                // Lay out glyph positions using atlas metrics.
                let mut laid_out_symbols: Vec<rustial_engine::symbols::PlacedSymbol> = symbols.to_vec();
                rustial_engine::symbols::layout_symbol_glyphs(
                    &mut laid_out_symbols,
                    &self.symbol_glyph_atlas,
                );

                // Build the symbol geometry batch.
                self.cached_symbol_batch = build_symbol_batch(
                    params.device,
                    &laid_out_symbols,
                    &self.symbol_glyph_atlas,
                    scene_camera_origin,
                    self.symbol_glyph_atlas.render_em_px(),
                );
            } else {
                self.cached_symbol_batch = None;
                self.symbol_atlas_bind_group = None;
                self.symbol_atlas_texture = None;
            }
        }

        // Build placeholder quad batch for loading tiles.
        self.cached_placeholder_batch = build_placeholder_batches(
            params.device,
            &frame.placeholders,
            params.state.placeholder_style(),
            scene_camera_origin,
        );

        // Build image overlay batches.
        self.build_image_overlay_batches(
            params.device,
            params.queue,
            &frame.image_overlays,
            scene_camera_origin,
        );

        // Ensure shared terrain resources are prepared before render pass.
        if use_shared_terrain {
            for mesh in terrain_meshes {
                self.get_or_create_shared_grid(params.device, mesh.grid_resolution);
                let scene_origin = scene_camera_origin;
                // Prepare terrain tile bind groups for all three pipeline kinds.
                self.get_or_create_terrain_tile_bind(
                    params.device, params.queue, mesh, params.state, scene_origin,
                    TerrainPipelineKind::Terrain,
                );
                self.get_or_create_terrain_tile_bind(
                    params.device, params.queue, mesh, params.state, scene_origin,
                    TerrainPipelineKind::TerrainData,
                );
                self.get_or_create_terrain_tile_bind(
                    params.device, params.queue, mesh, params.state, scene_origin,
                    TerrainPipelineKind::Hillshade,
                );
            }
        }

        let grid_scalar_overlays: Vec<_> = visualization
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::GridScalar { .. } => Some(overlay),
                _ => None,
            })
            .collect();
        let visible_grid_scalar_overlays: Vec<_> = grid_scalar_overlays
            .iter()
            .copied()
            .filter(|overlay| visualization_overlay_intersects_scene_viewport(overlay, params.state))
            .collect();
        let grid_extrusion_overlays: Vec<_> = visualization
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::GridExtrusion { .. } => Some(overlay),
                _ => None,
            })
            .collect();
        let visible_grid_extrusion_overlays: Vec<_> = grid_extrusion_overlays
            .iter()
            .copied()
            .filter(|overlay| visualization_overlay_intersects_scene_viewport(overlay, params.state))
            .collect();
        let column_overlays: Vec<_> = visualization
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::Columns { .. } => Some(overlay),
                _ => None,
            })
            .collect();
        let visible_column_overlays: Vec<_> = column_overlays
            .iter()
            .copied()
            .filter(|overlay| visualization_overlay_intersects_scene_viewport(overlay, params.state))
            .collect();
        let point_cloud_overlays: Vec<_> = visualization
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::Points { .. } => Some(overlay),
                _ => None,
            })
            .collect();
        let visible_point_cloud_overlays: Vec<_> = point_cloud_overlays
            .iter()
            .copied()
            .filter(|overlay| visualization_overlay_intersects_scene_viewport(overlay, params.state))
            .collect();
        let terrain_fingerprint = TerrainDataDirtyState::terrain_fingerprint(terrain_meshes);
        if !visible_grid_scalar_overlays.is_empty() {
            for overlay in &visible_grid_scalar_overlays {
                self.get_or_create_grid_scalar_overlay(
                    params.device,
                    params.queue,
                    overlay,
                    params.state,
                    scene_camera_origin,
                    terrain_fingerprint,
                );
            }
        }
        if !visible_column_overlays.is_empty() {
            self.get_or_create_shared_column_mesh(params.device);
            for overlay in &visible_column_overlays {
                self.get_or_create_column_overlay(
                    params.device,
                    params.queue,
                    overlay,
                    params.state,
                    scene_camera_origin,
                );
            }
        }
        if !visible_point_cloud_overlays.is_empty() {
            self.get_or_create_shared_column_mesh(params.device);
            for overlay in &visible_point_cloud_overlays {
                self.get_or_create_point_cloud_overlay(
                    params.device,
                    params.queue,
                    overlay,
                    params.state,
                    scene_camera_origin,
                );
            }
        }
        if !visible_grid_extrusion_overlays.is_empty() {
            for overlay in &visible_grid_extrusion_overlays {
                self.get_or_create_grid_extrusion_overlay(
                    params.device,
                    params.queue,
                    overlay,
                    params.state,
                    scene_camera_origin,
                    terrain_fingerprint,
                );
            }
        }

        // ?? 6. Render pass ??????????????????????????????????????????????
        let mut encoder = params
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("rustial_encoder"),
            });

        let has_heatmap = !self.cached_heatmap_batches.is_empty()
            && self.cached_heatmap_batches.iter().any(|b| b.is_some());

        let painter_plan = PainterPlan::new(
            !terrain_meshes.is_empty(),
            !params.state.hillshade_rasters().is_empty(),
            has_heatmap,
        );

        for painter_pass in painter_plan.iter() {
            match painter_pass {
                PainterPass::SkyAtmosphere => {
                    let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                         label: Some("rustial_pass_sky_atmosphere"),
                         color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                             view: params.color_view,
                             resolve_target: None,
                             ops: wgpu::Operations {
                                 load: wgpu::LoadOp::Clear(wgpu::Color {
                                    r: clear_color[0] as f64,
                                    g: clear_color[1] as f64,
                                    b: clear_color[2] as f64,
                                    a: clear_color[3] as f64,
                                 }),
                                 store: wgpu::StoreOp::Store,
                             },
                        })],
                        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                            view: &self.depth_view,
                            depth_ops: Some(wgpu::Operations {
                                load: wgpu::LoadOp::Clear(1.0),
                                store: wgpu::StoreOp::Store,
                            }),
                            stencil_ops: None,
                        }),
                        ..Default::default()
                    });
                }
                PainterPass::TerrainData => {
                    // Conditional terrain-data refresh: skip redrawing
                    // the depth / coordinate interaction buffers when the
                    // view-projection matrix and the terrain tile set
                    // haven't changed since the last render.  This mirrors
                    // MapLibre's `maybeDrawDepthAndCoords(false)` pattern.
                    if !self.terrain_data_dirty.needs_update(&vp, terrain_meshes) {
                        continue;
                    }
                    {
                        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                            label: Some("rustial_pass_terrain_data"),
                            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                                view: self.terrain_interaction_buffers.coord_view(),
                                resolve_target: None,
                                ops: wgpu::Operations {
                                    load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                                    store: wgpu::StoreOp::Store,
                                },
                            })],
                            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                                view: self.terrain_interaction_buffers.depth_view(),
                                depth_ops: Some(wgpu::Operations {
                                    load: wgpu::LoadOp::Clear(1.0),
                                    store: wgpu::StoreOp::Store,
                                }),
                                stencil_ops: None,
                            }),
                            ..Default::default()
                        });
                        if use_shared_terrain {
                            self.render_shared_terrain_data_tiles(
                                &mut pass,
                                params.state,
                                terrain_meshes,
                            );
                        } else {
                            self.render_terrain_data_batches(&mut pass, &terrain_batches);
                        }
                    }
                    self.terrain_data_dirty.mark_clean(&vp, terrain_meshes);
                }
                PainterPass::OpaqueScene => {
                    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("rustial_pass_opaque"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: params.color_view,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                 load: wgpu::LoadOp::Load,
                                 store: wgpu::StoreOp::Store,
                            },
                        })],
                        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                            view: &self.depth_view,
                            depth_ops: Some(wgpu::Operations {
                                load: wgpu::LoadOp::Load,
                                store: wgpu::StoreOp::Store,
                            }),
                            stencil_ops: None,
                        }),
                        ..Default::default()
                    });

                    // Draw loading placeholder quads behind tiles so
                    // loaded imagery naturally occludes them.
                    if let Some(ref ph_batch) = self.cached_placeholder_batch {
                        pass.set_pipeline(&self.vector_pipeline.pipeline);
                        pass.set_bind_group(0, &self.vector_uniform_bind_group, &[]);
                        pass.set_vertex_buffer(0, ph_batch.vertex_buffer.slice(..));
                        pass.set_index_buffer(
                            ph_batch.index_buffer.slice(..),
                            wgpu::IndexFormat::Uint32,
                        );
                        pass.draw_indexed(0..ph_batch.index_count, 0, 0..1);
                    }

                    if use_shared_terrain {
                        self.render_shared_terrain_tiles(
                            &mut pass,
                            params.state,
                            terrain_meshes,
                            params.visible_tiles,
                        );
                    } else if !terrain_batches.is_empty() {
                        self.render_terrain_batches(&mut pass, &terrain_batches);
                    } else {
                        self.render_tile_batches(&mut pass, &self.cached_tile_batches);
                    }

                    if !visible_grid_scalar_overlays.is_empty() {
                        self.render_grid_scalar_overlays(&mut pass, &visible_grid_scalar_overlays);
                    }
                    if !visible_grid_extrusion_overlays.is_empty() {
                        self.render_grid_extrusion_overlays(&mut pass, &visible_grid_extrusion_overlays);
                    }
                    if !visible_column_overlays.is_empty() {
                        self.render_column_overlays(&mut pass, &visible_column_overlays);
                    }
                    if !visible_point_cloud_overlays.is_empty() {
                        self.render_point_cloud_overlays(&mut pass, &visible_point_cloud_overlays);
                    }

                    self.render_vector_batches(&mut pass, &self.cached_vector_batches);
                    self.render_fill_batches(&mut pass, &self.cached_fill_batches);
                    self.render_fill_pattern_batches(&mut pass, &self.cached_fill_pattern_batches);
                    self.render_fill_extrusion_batches(&mut pass, &self.cached_fill_extrusion_batches);
                    self.render_line_batches(&mut pass, &self.cached_line_batches);
                    self.render_line_pattern_batches(&mut pass, &self.cached_line_pattern_batches);
                    self.render_circle_batches(&mut pass, &self.cached_circle_batches);
                    // Heatmap is now rendered in its own two-pass pipeline
                    // (HeatmapAccumulation → HeatmapColormap) rather than
                    // directly into the opaque scene.
                    self.render_image_overlay_batches(&mut pass);
                    self.render_symbol_batch(&mut pass);

                    if !params.model_instances.is_empty() {
                        self.render_models(
                            &mut pass,
                            params.model_instances,
                            params.device,
                        );
                    }
                }
                PainterPass::HeatmapAccumulation => {
                    // Pass 1: Render Gaussian-weighted heatmap points into
                    // the off-screen R16Float accumulation texture.
                    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("rustial_pass_heatmap_accum"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: &self.heatmap_accum_view,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Clear(wgpu::Color {
                                    r: 0.0,
                                    g: 0.0,
                                    b: 0.0,
                                    a: 0.0,
                                }),
                                store: wgpu::StoreOp::Store,
                            },
                        })],
                        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                            view: &self.depth_view,
                            depth_ops: Some(wgpu::Operations {
                                load: wgpu::LoadOp::Load,
                                store: wgpu::StoreOp::Store,
                            }),
                            stencil_ops: None,
                        }),
                        ..Default::default()
                    });
                    self.render_heatmap_batches(&mut pass, &self.cached_heatmap_batches);
                }
                PainterPass::HeatmapColormap => {
                    // Pass 2: Fullscreen triangle reads the accumulated
                    // weight texture and maps it through a colour ramp,
                    // compositing onto the main surface.
                    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("rustial_pass_heatmap_colormap"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: params.color_view,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Load,
                                store: wgpu::StoreOp::Store,
                            },
                        })],
                        depth_stencil_attachment: None,
                        ..Default::default()
                    });
                    pass.set_pipeline(&self.heatmap_colormap_pipeline.pipeline);
                    pass.set_bind_group(0, &self.heatmap_colormap_uniform_bind_group, &[]);
                    pass.set_bind_group(1, &self.heatmap_colormap_textures_bind_group, &[]);
                    pass.draw(0..3, 0..1); // fullscreen triangle
                }
                PainterPass::HillshadeOverlay => {
                    let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("rustial_pass_hillshade_overlay"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: params.color_view,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Load,
                                store: wgpu::StoreOp::Store,
                            },
                        })],
                        depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                            view: &self.depth_view,
                            depth_ops: Some(wgpu::Operations {
                                load: wgpu::LoadOp::Load,
                                store: wgpu::StoreOp::Store,
                            }),
                            stencil_ops: None,
                        }),
                        ..Default::default()
                    });

                    if use_shared_terrain {
                        self.render_shared_hillshade_tiles(
                            &mut pass,
                            params.state,
                            terrain_meshes,
                        );
                    } else {
                        self.render_hillshade_batches(&mut pass, &hillshade_batches);
                    }
                }
            }
        }

         // ?? 7. Submit ???????????????????????????????????????????????????
         params.queue.submit(std::iter::once(encoder.finish()));

        self.prune_height_texture_cache(terrain_meshes);
        self.prune_terrain_tile_bind_cache(terrain_meshes);
        self.prune_grid_scalar_overlay_cache(&grid_scalar_overlays);
        self.prune_grid_extrusion_overlay_cache(&grid_extrusion_overlays);
        self.prune_column_overlay_cache(&column_overlays);
        self.prune_point_cloud_overlay_cache(&point_cloud_overlays);

        // ?? 8. Atlas end-of-frame eviction ??????????????????????????????
        let tile_count_before = self.tile_atlas.len();
        self.tile_atlas.end_frame();
        if self.tile_atlas.len() != tile_count_before {
            self.tile_batch_cache_key = None;
        }
        self.hillshade_atlas.end_frame();
    }

    // -- Batched tile rendering -------------------------------------------

    /// Issue one `draw_indexed` per atlas page that has visible tile geometry.
    fn render_tile_batches<'a>(
         &'a self,
         pass: &mut wgpu::RenderPass<'a>,
         batches: &'a [TilePageBatches],
     ) {
        pass.set_bind_group(0, &self.uniform_bind_group, &[]);

        for (page_idx, batch) in batches.iter().enumerate() {
            let bg = match self.page_bind_groups.get(page_idx) {
                 Some(bg) => bg,
                 None => continue,
             };

            if let Some(batch) = batch.opaque.as_ref() {
                pass.set_pipeline(&self.tile_pipeline.pipeline);
                pass.set_bind_group(1, bg, &[]);
                pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
                pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..batch.index_count, 0, 0..1);
            }

            if let Some(batch) = batch.translucent.as_ref() {
                pass.set_pipeline(&self.tile_pipeline.translucent_pipeline);
                pass.set_bind_group(1, bg, &[]);
                pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
                pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..batch.index_count, 0, 0..1);
            }
        }
    }

    fn render_grid_scalar_overlays<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        overlays: &[&'a VisualizationOverlay],
    ) {
        pass.set_pipeline(&self.grid_scalar_pipeline.pipeline);
        pass.set_bind_group(0, &self.grid_scalar_uniform_bind_group, &[]);

        for overlay in overlays {
            let VisualizationOverlay::GridScalar { layer_id, .. } = overlay else {
                continue;
            };
            let Some(cached) = self.grid_scalar_overlay_cache.get(layer_id) else {
                continue;
            };
            pass.set_bind_group(1, &cached.bind_group, &[]);
            pass.set_vertex_buffer(0, cached.vertex_buffer.slice(..));
            pass.set_index_buffer(cached.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..cached.index_count, 0, 0..1);
        }
    }

    fn render_grid_extrusion_overlays<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        overlays: &[&'a VisualizationOverlay],
    ) {
        pass.set_pipeline(&self.grid_extrusion_pipeline.pipeline);
        pass.set_bind_group(0, &self.grid_extrusion_uniform_bind_group, &[]);

        for overlay in overlays {
            let VisualizationOverlay::GridExtrusion { layer_id, .. } = overlay else {
                continue;
            };
            let Some(cached) = self.grid_extrusion_overlay_cache.get(layer_id) else {
                continue;
            };
            pass.set_vertex_buffer(0, cached.vertex_buffer.slice(..));
            pass.set_index_buffer(cached.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..cached.index_count, 0, 0..1);
        }
    }

    fn render_column_overlays<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        overlays: &[&'a VisualizationOverlay],
    ) {
        let Some(mesh) = self.shared_column_mesh.as_ref() else {
            return;
        };

        pass.set_pipeline(&self.column_pipeline.pipeline);
        pass.set_bind_group(0, &self.column_uniform_bind_group, &[]);

        for overlay in overlays {
            let VisualizationOverlay::Columns { layer_id, .. } = overlay else {
                continue;
            };
            let Some(cached) = self.column_overlay_cache.get(layer_id) else {
                continue;
            };
            if cached.instance_count == 0 {
                continue;
            }
            pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
            pass.set_vertex_buffer(1, cached.instance_buffer.slice(..));
            pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..mesh.index_count, 0, 0..cached.instance_count);
        }
    }

    fn render_point_cloud_overlays<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        overlays: &[&'a VisualizationOverlay],
    ) {
        let Some(mesh) = self.shared_column_mesh.as_ref() else {
            return;
        };

        pass.set_pipeline(&self.column_pipeline.pipeline);
        pass.set_bind_group(0, &self.column_uniform_bind_group, &[]);

        for overlay in overlays {
            let VisualizationOverlay::Points { layer_id, .. } = overlay else {
                continue;
            };
            let Some(cached) = self.point_cloud_overlay_cache.get(layer_id) else {
                continue;
            };
            if cached.instance_count == 0 {
                continue;
            }
            pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
            pass.set_vertex_buffer(1, cached.instance_buffer.slice(..));
            pass.set_index_buffer(mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..mesh.index_count, 0, 0..cached.instance_count);
        }
    }

    // -- Batched terrain rendering ----------------------------------------

    /// Issue one `draw_indexed` per atlas page that has terrain geometry.
    fn render_terrain_batches<'a>(
         &'a self,
         pass: &mut wgpu::RenderPass<'a>,
         batches: &'a [Option<TerrainBatch>],
     ) {
        pass.set_pipeline(&self.terrain_pipeline.pipeline);
        pass.set_bind_group(0, &self.terrain_uniform_bind_group, &[]);

        for (page_idx, batch) in batches.iter().enumerate() {
             let batch = match batch {
                 Some(b) => b,
                 None => continue,
             };
            let bg = match self.page_terrain_bind_groups.get(page_idx) {
                 Some(bg) => bg,
                 None => continue,
             };

            pass.set_bind_group(1, bg, &[]);
            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    /// Issue one `draw_indexed` per terrain batch into the renderer-owned
    /// depth / coordinate buffers.
    fn render_terrain_data_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<TerrainBatch>],
    ) {
        pass.set_pipeline(&self.terrain_data_pipeline.pipeline);
        pass.set_bind_group(0, &self.terrain_data_uniform_bind_group, &[]);

        for batch in batches.iter().flatten() {
            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    // -- Batched hillshade rendering -------------------------------------

    /// Issue one `draw_indexed` per atlas page that has hillshade geometry.
    fn render_hillshade_batches<'a>(
         &'a self,
         pass: &mut wgpu::RenderPass<'a>,
         batches: &'a [Option<HillshadeBatch>],
     ) {
        pass.set_pipeline(&self.hillshade_pipeline.pipeline);
        pass.set_bind_group(0, &self.hillshade_uniform_bind_group, &[]);

        for (page_idx, batch) in batches.iter().enumerate() {
             let batch = match batch {
                 Some(b) => b,
                 None => continue,
             };
            let bg = match self.page_hillshade_bind_groups.get(page_idx) {
                 Some(bg) => bg,
                 None => continue,
             };

            pass.set_bind_group(1, bg, &[]);
            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    // -- Batched vector rendering -----------------------------------------

    /// Draw each non-empty vector layer.  Pipeline state is set lazily on
    /// the first actual draw to avoid overhead when there are no vectors.
    fn render_vector_batches<'a>(
         &'a self,
         pass: &mut wgpu::RenderPass<'a>,
         batches: &'a [Option<VectorBatchEntry>],
     ) {
        let mut pipeline_set = false;

        for batch in batches.iter().flatten() {
            if !pipeline_set {
                pass.set_pipeline(&self.vector_pipeline.pipeline);
                pass.set_bind_group(0, &self.vector_uniform_bind_group, &[]);
                pipeline_set = true;
            }

            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    // -- Batched fill rendering -------------------------------------------

    /// Draw each non-empty fill layer with per-batch fill params.
    fn render_fill_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<FillBatchEntry>],
    ) {
        for batch in batches.iter().flatten() {
            pass.set_pipeline(&self.fill_pipeline.pipeline);
            // Each batch has its own bind group (view-proj + fill params).
            pass.set_bind_group(0, &batch.bind_group, &[]);
            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    // -- Batched fill-pattern rendering ------------------------------------

    /// Draw each non-empty fill-pattern layer with texture sampling.
    fn render_fill_pattern_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<FillPatternBatchEntry>],
    ) {
        for batch in batches.iter().flatten() {
            pass.set_pipeline(&self.fill_pattern_pipeline.pipeline);
            pass.set_bind_group(0, &batch.uniform_bind_group, &[]);
            pass.set_bind_group(1, &batch.texture_bind_group, &[]);
            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    // -- Batched fill-extrusion rendering ---------------------------------

    /// Draw each non-empty fill-extrusion layer with per-face lighting.
    fn render_fill_extrusion_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<FillExtrusionBatchEntry>],
    ) {
        let mut pipeline_set = false;

        for batch in batches.iter().flatten() {
            if !pipeline_set {
                pass.set_pipeline(&self.fill_extrusion_pipeline.pipeline);
                pass.set_bind_group(0, &self.fill_extrusion_uniform_bind_group, &[]);
                pipeline_set = true;
            }

            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    fn render_line_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<LineBatchEntry>],
    ) {
        let mut pipeline_set = false;

        for batch in batches.iter().flatten() {
            if !pipeline_set {
                pass.set_pipeline(&self.line_pipeline.pipeline);
                pass.set_bind_group(0, &self.line_uniform_bind_group, &[]);
                pipeline_set = true;
            }

            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    fn render_line_pattern_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<LinePatternBatchEntry>],
    ) {
        for batch in batches.iter().flatten() {
            pass.set_pipeline(&self.line_pattern_pipeline.pipeline);
            pass.set_bind_group(0, &batch.uniform_bind_group, &[]);
            pass.set_bind_group(1, &batch.texture_bind_group, &[]);
            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    fn render_circle_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<CircleBatchEntry>],
    ) {
        let mut pipeline_set = false;

        for batch in batches.iter().flatten() {
            if !pipeline_set {
                pass.set_pipeline(&self.circle_pipeline.pipeline);
                pass.set_bind_group(0, &self.circle_uniform_bind_group, &[]);
                pipeline_set = true;
            }

            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    fn render_heatmap_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        batches: &'a [Option<HeatmapBatchEntry>],
    ) {
        let mut pipeline_set = false;

        for batch in batches.iter().flatten() {
            if !pipeline_set {
                pass.set_pipeline(&self.heatmap_pipeline.pipeline);
                pass.set_bind_group(0, &self.heatmap_uniform_bind_group, &[]);
                pipeline_set = true;
            }

            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..batch.index_count, 0, 0..1);
        }
    }

    // -- Image overlay batches ---------------------------------------------

    /// Build GPU batches for image overlays.  Reuses textures and bind
    /// groups from the previous frame when the overlay data has not
    /// changed (Arc pointer identity) or when only the geometry moved
    /// (same dimensions → `write_texture` instead of recreating).
    fn build_image_overlay_batches(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        overlays: &[rustial_engine::layers::ImageOverlayData],
        camera_origin: glam::DVec3,
    ) {
        // Take the old cache so we can harvest reusable entries.
        let mut old_cache: Vec<CachedImageOverlayBatch> =
            std::mem::take(&mut self.cached_image_overlay_batches);

        for overlay in overlays {
            if overlay.width == 0 || overlay.height == 0 || overlay.data.is_empty() {
                continue;
            }

            let data_arc_ptr = Arc::as_ptr(&overlay.data) as usize;

            // Try to find a matching cached entry (by layer id).
            let cached_idx = old_cache
                .iter()
                .position(|c| c.layer_id == overlay.layer_id);

            // Corner UVs: [top-left, top-right, bottom-right, bottom-left]
            let uvs = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
            let vertices: Vec<ImageOverlayVertex> = overlay
                .corners
                .iter()
                .zip(uvs.iter())
                .map(|(corner, uv)| {
                    let rel = [
                        (corner[0] - camera_origin.x) as f32,
                        (corner[1] - camera_origin.y) as f32,
                        (corner[2] - camera_origin.z) as f32,
                    ];
                    ImageOverlayVertex {
                        position: rel,
                        uv: *uv,
                        opacity: overlay.opacity,
                    }
                })
                .collect();
            let indices: Vec<u32> = vec![0, 1, 2, 0, 2, 3];

            if let Some(idx) = cached_idx {
                let mut cached = old_cache.remove(idx);

                // Always rebuild vertex/index (positions may have changed).
                cached.vertex_buffer =
                    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                        label: Some("image_overlay_vb"),
                        contents: bytemuck::cast_slice(&vertices),
                        usage: wgpu::BufferUsages::VERTEX,
                    });
                cached.index_buffer =
                    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                        label: Some("image_overlay_ib"),
                        contents: bytemuck::cast_slice(&indices),
                        usage: wgpu::BufferUsages::INDEX,
                    });

                // If data pointer is identical, skip texture re-upload.
                if cached.data_arc_ptr != data_arc_ptr {
                    if cached.tex_dimensions == (overlay.width, overlay.height) {
                        // Same dimensions → write_texture (no reallocation).
                        queue.write_texture(
                            wgpu::TexelCopyTextureInfo {
                                texture: &cached.texture,
                                mip_level: 0,
                                origin: wgpu::Origin3d::ZERO,
                                aspect: wgpu::TextureAspect::All,
                            },
                            &overlay.data,
                            wgpu::TexelCopyBufferLayout {
                                offset: 0,
                                bytes_per_row: Some(overlay.width * 4),
                                rows_per_image: Some(overlay.height),
                            },
                            wgpu::Extent3d {
                                width: overlay.width,
                                height: overlay.height,
                                depth_or_array_layers: 1,
                            },
                        );
                    } else {
                        // Dimensions changed → recreate texture + bind group.
                        let (texture, texture_view, texture_bind_group) =
                            self.create_overlay_texture(device, queue, overlay);
                        cached.texture = texture;
                        cached.texture_view = texture_view;
                        cached.texture_bind_group = texture_bind_group;
                        cached.tex_dimensions = (overlay.width, overlay.height);
                    }
                    cached.data_arc_ptr = data_arc_ptr;
                }

                self.cached_image_overlay_batches.push(cached);
            } else {
                // New overlay — full creation.
                let vertex_buffer =
                    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                        label: Some("image_overlay_vb"),
                        contents: bytemuck::cast_slice(&vertices),
                        usage: wgpu::BufferUsages::VERTEX,
                    });
                let index_buffer =
                    device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                        label: Some("image_overlay_ib"),
                        contents: bytemuck::cast_slice(&indices),
                        usage: wgpu::BufferUsages::INDEX,
                    });
                let (texture, texture_view, texture_bind_group) =
                    self.create_overlay_texture(device, queue, overlay);

                self.cached_image_overlay_batches.push(CachedImageOverlayBatch {
                    vertex_buffer,
                    index_buffer,
                    texture,
                    texture_view,
                    texture_bind_group,
                    layer_id: overlay.layer_id,
                    tex_dimensions: (overlay.width, overlay.height),
                    data_arc_ptr,
                });
            }
        }
        // old_cache entries not matched are dropped (stale overlays).
    }

    /// Create a new GPU texture + bind group for an image overlay.
    fn create_overlay_texture(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        overlay: &rustial_engine::layers::ImageOverlayData,
    ) -> (wgpu::Texture, wgpu::TextureView, wgpu::BindGroup) {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("image_overlay_tex"),
            size: wgpu::Extent3d {
                width: overlay.width,
                height: overlay.height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        queue.write_texture(
            wgpu::TexelCopyTextureInfo {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            &overlay.data,
            wgpu::TexelCopyBufferLayout {
                offset: 0,
                bytes_per_row: Some(overlay.width * 4),
                rows_per_image: Some(overlay.height),
            },
            wgpu::Extent3d {
                width: overlay.width,
                height: overlay.height,
                depth_or_array_layers: 1,
            },
        );
        let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let texture_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("image_overlay_tex_bg"),
            layout: &self.image_overlay_pipeline.texture_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&texture_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
            ],
        });
        (texture, texture_view, texture_bind_group)
    }

    /// Draw all cached image overlay batches.
    fn render_image_overlay_batches<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
    ) {
        if self.cached_image_overlay_batches.is_empty() {
            return;
        }
        pass.set_pipeline(&self.image_overlay_pipeline.pipeline);
        pass.set_bind_group(0, &self.image_overlay_uniform_bind_group, &[]);
        for batch in &self.cached_image_overlay_batches {
            pass.set_bind_group(1, &batch.texture_bind_group, &[]);
            pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
            pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
            pass.draw_indexed(0..6, 0, 0..1);
        }
    }

    fn render_symbol_batch<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
    ) {
        let batch = match &self.cached_symbol_batch {
            Some(b) => b,
            None => return,
        };
        let atlas_bg = match &self.symbol_atlas_bind_group {
            Some(bg) => bg,
            None => return,
        };

        pass.set_pipeline(&self.symbol_pipeline.pipeline);
        pass.set_bind_group(0, &self.symbol_uniform_bind_group, &[]);
        pass.set_bind_group(1, atlas_bg, &[]);
        pass.set_vertex_buffer(0, batch.vertex_buffer.slice(..));
        pass.set_index_buffer(batch.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
        pass.draw_indexed(0..batch.index_count, 0, 0..1);
    }

    fn render_models<'a>(
         &'a self,
         pass: &mut wgpu::RenderPass<'a>,
         model_instances: &[ModelInstance],
         device: &wgpu::Device,
    ) {
        if model_instances.is_empty() {
            return;
        }

        let cached = match &self.cached_model_transforms {
            Some(c) if c.instance_count == model_instances.len() => c,
            _ => return,
        };

        pass.set_pipeline(&self.model_pipeline.pipeline);
        pass.set_bind_group(0, &self.model_uniform_bind_group, &[]);

        for (i, instance) in model_instances.iter().enumerate() {
            let dyn_offset = (i * cached.stride) as u32;
            let mesh_key = ModelMeshKey::from_mesh(&instance.mesh);
            let cached_mesh = self.model_mesh_cache.get(&mesh_key);

            if let Some(cached_mesh) = cached_mesh {
                pass.set_bind_group(1, &cached.bind_group, &[dyn_offset]);
                pass.set_vertex_buffer(0, cached_mesh.vertex_buffer.slice(..));
                pass.set_index_buffer(cached_mesh.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..cached_mesh.index_count, 0, 0..1);
            } else {
                let vertices = build_model_vertices(&instance.mesh);
                let vb = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("model_inline_vb"),
                    contents: bytemuck::cast_slice(&vertices),
                    usage: wgpu::BufferUsages::VERTEX,
                });
                let ib = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some("model_inline_ib"),
                    contents: bytemuck::cast_slice(&instance.mesh.indices),
                    usage: wgpu::BufferUsages::INDEX,
                });
                let index_count = instance.mesh.indices.len() as u32;
                pass.set_bind_group(1, &cached.bind_group, &[dyn_offset]);
                pass.set_vertex_buffer(0, vb.slice(..));
                pass.set_index_buffer(ib.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..index_count, 0, 0..1);
            }
        }
    }

    /// Pre-cache model mesh GPU buffers before the render pass begins.
    ///
    /// Called automatically by [`render_full`](Self::render_full). This keeps
    /// stable model meshes resident on the GPU instead of re-uploading them
    /// every frame.
    pub fn cache_model_meshes(
        &mut self,
        device: &wgpu::Device,
        model_instances: &[ModelInstance],
    ) {
        for instance in model_instances {
            let key = ModelMeshKey::from_mesh(&instance.mesh);
            if self.model_mesh_cache.contains_key(&key) {
                continue;
            }

            let vertices = build_model_vertices(&instance.mesh);
            let vb = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("cached_model_vb"),
                contents: bytemuck::cast_slice(&vertices),
                usage: wgpu::BufferUsages::VERTEX,
            });
            let ib = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("cached_model_ib"),
                contents: bytemuck::cast_slice(&instance.mesh.indices),
                usage: wgpu::BufferUsages::INDEX,
            });

            self.model_mesh_cache.insert(
                key,
                CachedModelMesh {
                    vertex_buffer: vb,
                    index_buffer: ib,
                    index_count: instance.mesh.indices.len() as u32,
                },
            );
        }
    }

    /// Pre-build the model instance transform dynamic-UBO buffer and bind
    /// group.
    ///
    /// The buffer is only rebuilt when the transform fingerprint changes
    /// (instance positions, rotations, scales, or camera origin moved).
    /// On steady-state frames with a static model set and a stationary
    /// camera, this avoids the cost of `create_buffer_init` +
    /// `create_bind_group` entirely.
    fn cache_model_transforms(
        &mut self,
        device: &wgpu::Device,
        model_instances: &[ModelInstance],
        camera_origin: DVec3,
        state: &MapState,
    ) {
        let min_align = device.limits().min_uniform_buffer_offset_alignment as usize;
        let stride = 64_usize.div_ceil(min_align) * min_align;

        // Build a rolling fingerprint of the model transform inputs.
        let mut fp: u64 = model_instances.len() as u64;
        let origin_key = [
            (camera_origin.x * 100.0) as i64,
            (camera_origin.y * 100.0) as i64,
            (camera_origin.z * 100.0) as i64,
        ];
        fp = fp
            .wrapping_mul(31)
            .wrapping_add(origin_key[0] as u64)
            .wrapping_mul(31)
            .wrapping_add(origin_key[1] as u64)
            .wrapping_mul(31)
            .wrapping_add(origin_key[2] as u64);
        for instance in model_instances {
            fp = fp
                .wrapping_mul(31)
                .wrapping_add(instance.position.lat.to_bits())
                .wrapping_mul(31)
                .wrapping_add(instance.position.lon.to_bits())
                .wrapping_mul(31)
                .wrapping_add(instance.scale.to_bits())
                .wrapping_mul(31)
                .wrapping_add(instance.heading.to_bits());
        }

        if let Some(ref cached) = self.cached_model_transforms {
            if cached.fingerprint == fp && cached.instance_count == model_instances.len() {
                return;
            }
        }

        let mut transform_bytes = vec![0u8; stride * model_instances.len()];
        for (i, instance) in model_instances.iter().enumerate() {
            let terrain_elev = state.elevation_at(&instance.position);
            let altitude = instance.resolve_altitude(terrain_elev);

            let world_pos = state.camera().projection().project(&instance.position);
            let rel_x = (world_pos.position.x - camera_origin.x) as f32;
            let rel_y = (world_pos.position.y - camera_origin.y) as f32;
            let rel_z = (altitude - camera_origin.z) as f32;

            let scale = instance.scale as f32;
            let heading = instance.heading as f32;
            let pitch = instance.pitch as f32;
            let roll = instance.roll as f32;

            let rotation = glam::Quat::from_rotation_z(heading)
                * glam::Quat::from_rotation_x(pitch)
                * glam::Quat::from_rotation_y(roll);
            let transform = Mat4::from_translation(glam::Vec3::new(rel_x, rel_y, rel_z))
                * Mat4::from_quat(rotation)
                * Mat4::from_scale(glam::Vec3::splat(scale));

            let mat = transform.to_cols_array_2d();
            let mat_bytes = bytemuck::cast_slice(&mat);
            let offset = i * stride;
            transform_bytes[offset..offset + 64].copy_from_slice(mat_bytes);
        }

        let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("model_transforms_cached_buf"),
            contents: &transform_bytes,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        });

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("model_transforms_cached_bg"),
            layout: &self.model_pipeline.model_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: buffer.as_entire_binding(),
            }],
        });

        self.cached_model_transforms = Some(CachedModelTransforms {
            buffer,
            bind_group,
            stride,
            instance_count: model_instances.len(),
            fingerprint: fp,
        })
    }

    // -- Page bind group management ---------------------------------------

    /// Rebuild per-atlas-page bind groups when new atlas pages are created.
    fn rebuild_page_bind_groups(&mut self, device: &wgpu::Device) {
        let tile_pages = self.tile_atlas.page_count();
        while self.page_bind_groups.len() < tile_pages {
            let idx = self.page_bind_groups.len();
            let view = &self.tile_atlas.pages[idx].view;
            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(&format!("rustial_tile_page_bg_{idx}")),
                layout: &self.tile_pipeline.texture_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Sampler(&self.sampler),
                    },
                ],
            });
            self.page_bind_groups.push(bg);

            let terrain_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(&format!("rustial_terrain_page_bg_{idx}")),
                layout: &self.terrain_pipeline.texture_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Sampler(&self.sampler),
                    },
                ],
            });
            self.page_terrain_bind_groups.push(terrain_bg);
        }

        let hillshade_pages = self.hillshade_atlas.page_count();
        while self.page_hillshade_bind_groups.len() < hillshade_pages {
            let idx = self.page_hillshade_bind_groups.len();
            let view = &self.hillshade_atlas.pages[idx].view;
            let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(&format!("rustial_hillshade_page_bg_{idx}")),
                layout: &self.hillshade_pipeline.texture_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::TextureView(view),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Sampler(&self.sampler),
                    },
                ],
            });
            self.page_hillshade_bind_groups.push(bg);
        }
    }

    // -- Shared-grid terrain rendering ------------------------------------

    fn get_or_create_shared_grid(
        &mut self,
        device: &wgpu::Device,
        resolution: u16,
    ) -> &SharedTerrainGridMesh {
        if !self.shared_terrain_grids.contains_key(&resolution) {
            let (vertices, indices) = build_shared_terrain_grid(resolution as usize);
            let vb = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("terrain_grid_vb_{resolution}")),
                contents: bytemuck::cast_slice(&vertices),
                usage: wgpu::BufferUsages::VERTEX,
            });
            let ib = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(&format!("terrain_grid_ib_{resolution}")),
                contents: bytemuck::cast_slice(&indices),
                usage: wgpu::BufferUsages::INDEX,
            });
            self.shared_terrain_grids.insert(
                resolution,
                SharedTerrainGridMesh {
                    vertex_buffer: vb,
                    index_buffer: ib,
                    index_count: indices.len() as u32,
                },
            );
        }
        self.shared_terrain_grids.get(&resolution).unwrap()
    }

    fn get_or_create_terrain_tile_bind(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        mesh: &TerrainMeshData,
        state: &MapState,
        scene_origin: DVec3,
        pipeline_kind: TerrainPipelineKind,
    ) -> Option<()> {
        let elevation = mesh.elevation_texture.as_ref()?;
        let key = TerrainTileBindKey {
            tile: mesh.tile,
            pipeline: pipeline_kind,
        };
        let origin_key = [
            (scene_origin.x * 100.0) as i64,
            (scene_origin.y * 100.0) as i64,
            (scene_origin.z * 100.0) as i64,
        ];

        // Check if already cached and valid.
        if let Some(cached) = self.terrain_tile_bind_cache.get(&key) {
            if cached.origin_key == origin_key && cached.generation == mesh.generation {
                return Some(());
            }
        }

        // Ensure height texture is cached.
        let tile = mesh.tile;
        let gen = mesh.generation;
        let needs_height = self
            .height_texture_cache
            .get(&tile)
            .map_or(true, |c| c.generation != gen);
        if needs_height {
            let size = wgpu::Extent3d {
                width: elevation.width.max(1),
                height: elevation.height.max(1),
                depth_or_array_layers: 1,
            };
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some(&format!("height_tex_{:?}", tile)),
                size,
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::R32Float,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            });
            queue.write_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: &texture,
                    mip_level: 0,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                bytemuck::cast_slice(&elevation.data),
                wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(elevation.width.max(1) * 4),
                    rows_per_image: None,
                },
                size,
            );
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.height_texture_cache
                .insert(tile, CachedHeightTexture { generation: gen, view });
        }

        // Build the tile uniform and bind group.
        let tile_uniform = build_terrain_tile_uniform(mesh, elevation, state, scene_origin);

        let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some(&format!("terrain_tile_uniform_{:?}_{:?}", mesh.tile, pipeline_kind)),
            contents: bytemuck::bytes_of(&tile_uniform),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        });

        let layout = match pipeline_kind {
            TerrainPipelineKind::Terrain => &self.terrain_pipeline.tile_bind_group_layout,
            TerrainPipelineKind::TerrainData => &self.terrain_data_pipeline.tile_bind_group_layout,
            TerrainPipelineKind::Hillshade => &self.hillshade_pipeline.tile_bind_group_layout,
        };

        // Obtain the height texture view pointer safely.
        let height_view_ref = &self.height_texture_cache.get(&tile)?.view;
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some(&format!("terrain_tile_bg_{:?}_{:?}", mesh.tile, pipeline_kind)),
            layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(height_view_ref),
                },
            ],
        });

        self.terrain_tile_bind_cache.insert(
            key,
            CachedTerrainTileBind {
                uniform_buffer,
                bind_group,
                origin_key,
                generation: mesh.generation,
            },
        );
        Some(())
    }

    fn render_shared_terrain_tiles<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        _state: &MapState,
        terrain_meshes: &[TerrainMeshData],
        visible_tiles: &[VisibleTile],
    ) {
        pass.set_pipeline(&self.terrain_pipeline.pipeline);
        pass.set_bind_group(0, &self.terrain_uniform_bind_group, &[]);

        for mesh in terrain_meshes {
            let grid = match self.shared_terrain_grids.get(&mesh.grid_resolution) {
                Some(g) => g,
                None => continue,
            };

            if let Some(actual) = find_terrain_texture_actual(mesh.tile, visible_tiles) {
                if let Some(region) = self.tile_atlas.get(&actual) {
                    if let Some(bg) = self.page_terrain_bind_groups.get(region.page) {
                        pass.set_bind_group(1, bg, &[]);
                    }
                }
            }

            let key = TerrainTileBindKey {
                tile: mesh.tile,
                pipeline: TerrainPipelineKind::Terrain,
            };
            if let Some(cached) = self.terrain_tile_bind_cache.get(&key) {
                pass.set_bind_group(2, &cached.bind_group, &[]);
                pass.set_vertex_buffer(0, grid.vertex_buffer.slice(..));
                pass.set_index_buffer(grid.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..grid.index_count, 0, 0..1);
            }
        }
    }

    fn render_shared_terrain_data_tiles<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        _state: &MapState,
        terrain_meshes: &[TerrainMeshData],
    ) {
        pass.set_pipeline(&self.terrain_data_pipeline.pipeline);
        pass.set_bind_group(0, &self.terrain_data_uniform_bind_group, &[]);

        for mesh in terrain_meshes {
            let grid = match self.shared_terrain_grids.get(&mesh.grid_resolution) {
                Some(g) => g,
                None => continue,
            };

            let key = TerrainTileBindKey {
                tile: mesh.tile,
                pipeline: TerrainPipelineKind::TerrainData,
            };
            if let Some(cached) = self.terrain_tile_bind_cache.get(&key) {
                pass.set_bind_group(1, &cached.bind_group, &[]);
                pass.set_vertex_buffer(0, grid.vertex_buffer.slice(..));
                pass.set_index_buffer(grid.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..grid.index_count, 0, 0..1);
            }
        }
    }

    fn render_shared_hillshade_tiles<'a>(
        &'a self,
        pass: &mut wgpu::RenderPass<'a>,
        _state: &MapState,
        terrain_meshes: &[TerrainMeshData],
    ) {
        pass.set_pipeline(&self.hillshade_pipeline.pipeline);
        pass.set_bind_group(0, &self.hillshade_uniform_bind_group, &[]);

        for mesh in terrain_meshes {
            let grid = match self.shared_terrain_grids.get(&mesh.grid_resolution) {
                Some(g) => g,
                None => continue,
            };

            if let Some(region) = self.hillshade_atlas.get(&mesh.tile) {
                if let Some(bg) = self.page_hillshade_bind_groups.get(region.page) {
                    pass.set_bind_group(1, bg, &[]);
                }
            }

            let key = TerrainTileBindKey {
                tile: mesh.tile,
                pipeline: TerrainPipelineKind::Hillshade,
            };
            if let Some(cached) = self.terrain_tile_bind_cache.get(&key) {
                pass.set_bind_group(2, &cached.bind_group, &[]);
                pass.set_vertex_buffer(0, grid.vertex_buffer.slice(..));
                pass.set_index_buffer(grid.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(0..grid.index_count, 0, 0..1);
            }
        }
    }

    // -- Cache pruning ----------------------------------------------------

    fn prune_height_texture_cache(&mut self, terrain_meshes: &[TerrainMeshData]) {
        let live: std::collections::HashSet<TileId> =
            terrain_meshes.iter().map(|m| m.tile).collect();
        self.height_texture_cache.retain(|tile, _| live.contains(tile));
    }

    fn prune_terrain_tile_bind_cache(&mut self, terrain_meshes: &[TerrainMeshData]) {
        let live: std::collections::HashSet<TileId> =
            terrain_meshes.iter().map(|m| m.tile).collect();
        self.terrain_tile_bind_cache
            .retain(|key, _| live.contains(&key.tile));
    }

    fn prune_grid_scalar_overlay_cache(&mut self, overlays: &[&VisualizationOverlay]) {
        let live: std::collections::HashSet<LayerId> = overlays
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::GridScalar { layer_id, .. } => Some(*layer_id),
                _ => None,
            })
            .collect();
        self.grid_scalar_overlay_cache
            .retain(|layer_id, _| live.contains(layer_id));
    }

    fn prune_grid_extrusion_overlay_cache(&mut self, overlays: &[&VisualizationOverlay]) {
        let live: std::collections::HashSet<LayerId> = overlays
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::GridExtrusion { layer_id, .. } => Some(*layer_id),
                _ => None,
            })
            .collect();
        self.grid_extrusion_overlay_cache
            .retain(|layer_id, _| live.contains(layer_id));
    }

    fn prune_column_overlay_cache(&mut self, overlays: &[&VisualizationOverlay]) {
        let live: std::collections::HashSet<LayerId> = overlays
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::Columns { layer_id, .. } => Some(*layer_id),
                _ => None,
            })
            .collect();
        self.column_overlay_cache
            .retain(|layer_id, _| live.contains(layer_id));
    }

    fn prune_point_cloud_overlay_cache(&mut self, overlays: &[&VisualizationOverlay]) {
        let live: std::collections::HashSet<LayerId> = overlays
            .iter()
            .filter_map(|overlay| match overlay {
                VisualizationOverlay::Points { layer_id, .. } => Some(*layer_id),
                _ => None,
            })
            .collect();
        self.point_cloud_overlay_cache
            .retain(|layer_id, _| live.contains(layer_id));
    }

    // -- Headless capture -------------------------------------------------

    /// Render one full frame to an offscreen texture and return the pixel
    /// data as a `Vec<u8>` in RGBA8 format (4 bytes per pixel,
    /// `width * height * 4` total bytes).
    ///
    /// This is the primary entry-point for headless rendering and
    /// cross-renderer comparison tests.  It creates a transient
    /// colour texture, calls [`render_full`](Self::render_full), copies
    /// the result to a readback buffer, and returns the pixels.
    ///
    /// # Arguments
    ///
    /// * `state` - Engine map state (camera, layers, terrain).
    /// * `device` - WGPU device.
    /// * `queue` - WGPU queue.
    /// * `visible_tiles` - Tile set for this frame.
    /// * `vector_meshes` - Tessellated vector layers.
    /// * `model_instances` - 3D model instances.
    ///
    /// # Returns
    ///
    /// `Some(pixels)` on success, `None` if the GPU readback fails.
    pub fn render_to_buffer(
        &mut self,
        state: &MapState,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        visible_tiles: &[VisibleTile],
        vector_meshes: &[VectorMeshData],
        model_instances: &[ModelInstance],
    ) -> Option<Vec<u8>> {
        let format = wgpu::TextureFormat::Rgba8UnormSrgb;

        let color_tex = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("rustial_render_to_buffer_color"),
            size: wgpu::Extent3d {
                width: self.width,
                height: self.height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });
        let color_view = color_tex.create_view(&wgpu::TextureViewDescriptor::default());

        let clear_color = state.computed_fog().clear_color;

        self.render_full(&RenderParams {
            state,
            device,
            queue,
            color_view: &color_view,
            visible_tiles,
            vector_meshes,
            model_instances,
            clear_color,
        });

        let bytes_per_row = self.width * 4;
        let buffer_size = (bytes_per_row * self.height) as wgpu::BufferAddress;
        let readback = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("rustial_render_to_buffer_readback"),
            size: buffer_size,
            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
            mapped_at_creation: false,
        });

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("rustial_render_to_buffer_encoder"),
        });
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture: &color_tex,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &readback,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(bytes_per_row),
                    rows_per_image: Some(self.height),
                },
            },
            wgpu::Extent3d {
                width: self.width,
                height: self.height,
                depth_or_array_layers: 1,
            },
        );
        queue.submit(std::iter::once(encoder.finish()));

        let slice = readback.slice(..);
        let (tx, rx) = std::sync::mpsc::channel();
        slice.map_async(wgpu::MapMode::Read, move |res| {
            let _ = tx.send(res);
        });
        let _ = device.poll(wgpu::PollType::wait());
        rx.recv().ok()?.ok()?;

        let data = slice.get_mapped_range().to_vec();
        readback.unmap();
        Some(data)
    }

    /// Return the current renderer width in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Return the current renderer height in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Return per-frame visualization cache activity from the last render.
    pub fn visualization_perf_stats(&self) -> VisualizationPerfStats {
        self.visualization_perf_stats
    }

    /// Return atlas health diagnostics for the tile atlas.
    ///
    /// Useful for performance overlays and automated tests.  Call after
    /// [`render_full`](Self::render_full) for post-frame metrics, or at
    /// any time for the current snapshot.
    pub fn tile_atlas_diagnostics(&self) -> crate::gpu::tile_atlas::AtlasDiagnostics {
        self.tile_atlas.diagnostics()
    }

    /// Return atlas health diagnostics for the hillshade atlas.
    pub fn hillshade_atlas_diagnostics(&self) -> crate::gpu::tile_atlas::AtlasDiagnostics {
        self.hillshade_atlas.diagnostics()
    }
}

// ---------------------------------------------------------------------------
// Helpers (module-private)
// ---------------------------------------------------------------------------

fn build_grid_scalar_geometry(
    grid: &rustial_engine::GeoGrid,
    state: &MapState,
    scene_origin: DVec3,
) -> (Vec<GridScalarVertex>, Vec<u32>) {
    let rows = grid.rows.max(1);
    let cols = grid.cols.max(1);
    let mut vertices = Vec::with_capacity((rows + 1) * (cols + 1));
    let mut indices = Vec::with_capacity(rows * cols * 6);

    for row in 0..=rows {
        for col in 0..=cols {
            let u = col as f32 / cols as f32;
            let v = row as f32 / rows as f32;
            let coord = grid_corner_coord(grid, row, col, state);
            let projected = state.camera().projection().project(&coord);
            vertices.push(GridScalarVertex {
                position: [
                    (projected.position.x - scene_origin.x) as f32,
                    (projected.position.y - scene_origin.y) as f32,
                    (projected.position.z - scene_origin.z + 0.05) as f32,
                ],
                uv: [u, v],
            });
        }
    }

    for row in 0..rows {
        for col in 0..cols {
            let tl = (row * (cols + 1) + col) as u32;
            let tr = tl + 1;
            let bl = ((row + 1) * (cols + 1) + col) as u32;
            let br = bl + 1;
            indices.extend_from_slice(&[tl, bl, tr, tr, bl, br]);
        }
    }

    (vertices, indices)
}

fn grid_corner_coord(
    grid: &rustial_engine::GeoGrid,
    row: usize,
    col: usize,
    state: &MapState,
) -> rustial_math::GeoCoord {
    let dx = col as f64 * grid.cell_width;
    let dy = row as f64 * grid.cell_height;
    let (sin_r, cos_r) = grid.rotation.sin_cos();
    let rx = dx * cos_r - dy * sin_r;
    let ry = dx * sin_r + dy * cos_r;
    let coord = offset_geo_coord(&grid.origin, rx, ry);
    let altitude = resolve_grid_surface_altitude(grid, &coord, state);
    rustial_math::GeoCoord::new(coord.lat, coord.lon, altitude)
}

fn create_grid_scalar_texture(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    field: &rustial_engine::ScalarField2D,
) -> wgpu::Texture {
    let size = wgpu::Extent3d {
        width: field.cols.max(1) as u32,
        height: field.rows.max(1) as u32,
        depth_or_array_layers: 1,
    };
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("grid_scalar_field_texture"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::R32Float,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    write_grid_scalar_texture(queue, &texture, field);
    texture
}

fn write_grid_scalar_texture(
    queue: &wgpu::Queue,
    texture: &wgpu::Texture,
    field: &rustial_engine::ScalarField2D,
) {
    let size = wgpu::Extent3d {
        width: field.cols.max(1) as u32,
        height: field.rows.max(1) as u32,
        depth_or_array_layers: 1,
    };
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        bytemuck::cast_slice(&field.data),
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(field.cols.max(1) as u32 * 4),
            rows_per_image: Some(field.rows.max(1) as u32),
        },
        size,
    );
}

fn create_grid_scalar_ramp_texture(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    ramp: &rustial_engine::ColorRamp,
) -> wgpu::Texture {
    let width = 256u32;
    let data = ramp.as_texture_data(width);
    let size = wgpu::Extent3d {
        width,
        height: 1,
        depth_or_array_layers: 1,
    };
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("grid_scalar_ramp_texture"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8UnormSrgb,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        &data,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(width * 4),
            rows_per_image: Some(1),
        },
        size,
    );
    texture
}

// ---------------------------------------------------------------------------
// Heatmap two-pass helpers
// ---------------------------------------------------------------------------

/// Create the off-screen R16Float accumulation texture for heatmap Pass 1.
fn create_heatmap_accum_texture(
    device: &wgpu::Device,
    width: u32,
    height: u32,
) -> (wgpu::Texture, wgpu::TextureView) {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("heatmap_accum_texture"),
        size: wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::R16Float,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
        view_formats: &[],
    });
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    (texture, view)
}

/// Create a default 256×1 Rgba8Unorm heatmap colour ramp texture.
///
/// The ramp interpolates through: transparent → royal blue → cyan → lime →
/// yellow → red, matching the MapLibre default heat stops.
fn create_default_heatmap_ramp_texture(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
) -> wgpu::Texture {
    const WIDTH: u32 = 256;
    let stops: &[(f32, [u8; 4])] = &[
        (0.00, [0, 0, 0, 0]),
        (0.10, [65, 105, 225, 255]),
        (0.30, [0, 255, 255, 255]),
        (0.50, [0, 255, 0, 255]),
        (0.70, [255, 255, 0, 255]),
        (1.00, [255, 0, 0, 255]),
    ];

    let mut data = vec![0u8; WIDTH as usize * 4];
    for i in 0..WIDTH as usize {
        let t = i as f32 / (WIDTH - 1) as f32;
        // Find the two surrounding stops.
        let mut lo = 0;
        for s in 1..stops.len() {
            if stops[s].0 >= t {
                lo = s - 1;
                break;
            }
        }
        let hi = (lo + 1).min(stops.len() - 1);
        let range = stops[hi].0 - stops[lo].0;
        let frac = if range > 0.0 {
            (t - stops[lo].0) / range
        } else {
            0.0
        };
        for c in 0..4 {
            let a = stops[lo].1[c] as f32;
            let b = stops[hi].1[c] as f32;
            data[i * 4 + c] = (a + (b - a) * frac).round() as u8;
        }
    }

    let size = wgpu::Extent3d {
        width: WIDTH,
        height: 1,
        depth_or_array_layers: 1,
    };
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("heatmap_ramp_texture"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: wgpu::TextureFormat::Rgba8Unorm,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture: &texture,
            mip_level: 0,
            origin: wgpu::Origin3d::ZERO,
            aspect: wgpu::TextureAspect::All,
        },
        &data,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(WIDTH * 4),
            rows_per_image: Some(1),
        },
        size,
    );
    texture
}

/// Create the bind group for heatmap colour-mapping Pass 2 (group 1).
fn create_heatmap_colormap_bind_group(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    accum_view: &wgpu::TextureView,
    ramp_view: &wgpu::TextureView,
    sampler: &wgpu::Sampler,
) -> wgpu::BindGroup {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("heatmap_colormap_textures_bg"),
        layout,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::TextureView(accum_view),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: wgpu::BindingResource::TextureView(ramp_view),
            },
            wgpu::BindGroupEntry {
                binding: 2,
                resource: wgpu::BindingResource::Sampler(sampler),
            },
        ],
    })
}

fn build_grid_scalar_uniform(
    grid: &rustial_engine::GeoGrid,
    field: &rustial_engine::ScalarField2D,
    state: &MapState,
    scene_origin: DVec3,
    opacity: f32,
) -> GridScalarUniform {
    let projection_kind = match state.camera().projection() {
        rustial_engine::CameraProjection::WebMercator => 0.0,
        rustial_engine::CameraProjection::Equirectangular => 1.0,
        _ => 0.0,
    };
    let base_altitude = match grid.altitude_mode {
        rustial_engine::AltitudeMode::ClampToGround => 0.0,
        rustial_engine::AltitudeMode::RelativeToGround => grid.origin.alt as f32,
        rustial_engine::AltitudeMode::Absolute => grid.origin.alt as f32,
    };
    GridScalarUniform {
        origin_counts: [grid.origin.lat as f32, grid.origin.lon as f32, grid.rows as f32, grid.cols as f32],
        grid_params: [grid.cell_width as f32, grid.cell_height as f32, grid.rotation as f32, opacity],
        scene_origin: [scene_origin.x as f32, scene_origin.y as f32, scene_origin.z as f32, projection_kind],
        value_params: [
            field.min,
            field.max,
            field.nan_value.unwrap_or(0.0),
            if field.nan_value.is_some() { 1.0 } else { 0.0 },
        ],
        base_altitude: [base_altitude, 0.0, 0.0, 0.0],
    }
}

fn grid_scalar_ramp_fingerprint(ramp: &rustial_engine::ColorRamp) -> u64 {
    let mut h = ramp.stops.len() as u64;
    for stop in &ramp.stops {
        h = h
            .wrapping_mul(31)
            .wrapping_add(stop.value.to_bits() as u64)
            .wrapping_mul(31)
            .wrapping_add(stop.color[0].to_bits() as u64)
            .wrapping_mul(31)
            .wrapping_add(stop.color[1].to_bits() as u64)
            .wrapping_mul(31)
            .wrapping_add(stop.color[2].to_bits() as u64)
            .wrapping_mul(31)
            .wrapping_add(stop.color[3].to_bits() as u64);
    }
    h
}

fn grid_extrusion_params_fingerprint(params: &rustial_engine::ExtrusionParams) -> u64 {
    (params.height_scale.to_bits())
        .wrapping_mul(31)
        .wrapping_add(params.base_meters.to_bits())
}

fn grid_extrusion_grid_fingerprint(grid: &rustial_engine::GeoGrid) -> u64 {
    let mut h = 17u64;
    h = h.wrapping_mul(31).wrapping_add(grid.origin.lat.to_bits());
    h = h.wrapping_mul(31).wrapping_add(grid.origin.lon.to_bits());
    h = h.wrapping_mul(31).wrapping_add(grid.origin.alt.to_bits());
    h = h.wrapping_mul(31).wrapping_add(grid.rows as u64);
    h = h.wrapping_mul(31).wrapping_add(grid.cols as u64);
    h = h.wrapping_mul(31).wrapping_add(grid.cell_width.to_bits());
    h = h.wrapping_mul(31).wrapping_add(grid.cell_height.to_bits());
    h = h.wrapping_mul(31).wrapping_add(grid.rotation.to_bits());
    h = h.wrapping_mul(31).wrapping_add(match grid.altitude_mode {
        rustial_engine::AltitudeMode::ClampToGround => 0,
        rustial_engine::AltitudeMode::RelativeToGround => 1,
        rustial_engine::AltitudeMode::Absolute => 2,
    });
    h
}

fn build_grid_extrusion_geometry(
    grid: &rustial_engine::GeoGrid,
    field: &rustial_engine::ScalarField2D,
    ramp: &rustial_engine::ColorRamp,
    params: &rustial_engine::ExtrusionParams,
    state: &MapState,
    scene_origin: DVec3,
) -> (Vec<GridExtrusionVertex>, Vec<u32>) {
    let mut vertices = Vec::new();
    let mut indices = Vec::new();

    for row in 0..grid.rows {
        for col in 0..grid.cols {
            let Some(value) = field.sample(row, col) else {
                continue;
            };

            let t = field.normalized(row, col).unwrap_or(0.5);
            let color = ramp.evaluate(t);
            let corners = grid_cell_corners_world(grid, row, col, state, scene_origin, params);
            append_extruded_cell_geometry(
                &mut vertices,
                &mut indices,
                corners,
                (value as f32) * params.height_scale as f32,
                color,
            );
        }
    }

    (vertices, indices)
}

fn append_extruded_cell_geometry(
    vertices: &mut Vec<GridExtrusionVertex>,
    indices: &mut Vec<u32>,
    corners: [[f32; 3]; 4],
    extrusion_height: f32,
    color: [f32; 4],
) {
    let [nw, ne, sw, se] = corners;
    let top = [
        [nw[0], nw[1], nw[2] + extrusion_height],
        [ne[0], ne[1], ne[2] + extrusion_height],
        [sw[0], sw[1], sw[2] + extrusion_height],
        [se[0], se[1], se[2] + extrusion_height],
    ];
    let base = [
        nw,
        ne,
        sw,
        se,
    ];

    append_quad(vertices, indices, top[0], top[1], top[2], top[3], [0.0, 0.0, 1.0], color);
    append_quad(vertices, indices, base[0], base[1], top[0], top[1], [0.0, -1.0, 0.0], color);
    append_quad(vertices, indices, top[2], top[3], base[2], base[3], [0.0, 1.0, 0.0], color);
    append_quad(vertices, indices, base[0], top[0], base[2], top[2], [-1.0, 0.0, 0.0], color);
    append_quad(vertices, indices, top[1], base[1], top[3], base[3], [1.0, 0.0, 0.0], color);
}

fn append_quad(
    vertices: &mut Vec<GridExtrusionVertex>,
    indices: &mut Vec<u32>,
    a: [f32; 3],
    b: [f32; 3],
    c: [f32; 3],
    d: [f32; 3],
    normal: [f32; 3],
    color: [f32; 4],
) {
    let base_index = vertices.len() as u32;
    vertices.extend_from_slice(&[
        GridExtrusionVertex { position: a, normal, color },
        GridExtrusionVertex { position: b, normal, color },
        GridExtrusionVertex { position: c, normal, color },
        GridExtrusionVertex { position: d, normal, color },
    ]);
    indices.extend_from_slice(&[
        base_index,
        base_index + 2,
        base_index + 1,
        base_index + 1,
        base_index + 2,
        base_index + 3,
    ]);
}

fn grid_cell_corners_world(
    grid: &rustial_engine::GeoGrid,
    row: usize,
    col: usize,
    state: &MapState,
    scene_origin: DVec3,
    params: &rustial_engine::ExtrusionParams,
) -> [[f32; 3]; 4] {
    let nw = project_grid_offset(
        grid,
        col as f64 * grid.cell_width,
        row as f64 * grid.cell_height,
        state,
        scene_origin,
        params,
    );
    let ne = project_grid_offset(
        grid,
        (col + 1) as f64 * grid.cell_width,
        row as f64 * grid.cell_height,
        state,
        scene_origin,
        params,
    );
    let sw = project_grid_offset(
        grid,
        col as f64 * grid.cell_width,
        (row + 1) as f64 * grid.cell_height,
        state,
        scene_origin,
        params,
    );
    let se = project_grid_offset(
        grid,
        (col + 1) as f64 * grid.cell_width,
        (row + 1) as f64 * grid.cell_height,
        state,
        scene_origin,
        params,
    );
    [nw, ne, sw, se]
}

fn project_grid_offset(
    grid: &rustial_engine::GeoGrid,
    dx: f64,
    dy: f64,
    state: &MapState,
    scene_origin: DVec3,
    params: &rustial_engine::ExtrusionParams,
) -> [f32; 3] {
    let (sin_r, cos_r) = grid.rotation.sin_cos();
    let rx = dx * cos_r - dy * sin_r;
    let ry = dx * sin_r + dy * cos_r;
    let coord = offset_geo_coord(&grid.origin, rx, ry);
    let altitude = resolve_grid_base_altitude(grid, &coord, state, params) as f64;
    let elevated_coord = rustial_math::GeoCoord::new(coord.lat, coord.lon, altitude);
    let projected = state.camera().projection().project(&elevated_coord);
    [
        (projected.position.x - scene_origin.x) as f32,
        (projected.position.y - scene_origin.y) as f32,
        (projected.position.z - scene_origin.z) as f32,
    ]
}

fn offset_geo_coord(origin: &rustial_math::GeoCoord, dx_meters: f64, dy_meters: f64) -> rustial_math::GeoCoord {
    const METERS_PER_DEG_LAT: f64 = 111_320.0;
    let lat = origin.lat - dy_meters / METERS_PER_DEG_LAT;
    let cos_lat = origin.lat.to_radians().cos().max(1e-10);
    let lon = origin.lon + dx_meters / (METERS_PER_DEG_LAT * cos_lat);
    rustial_math::GeoCoord::new(lat, lon, origin.alt)
}

fn resolve_grid_base_altitude(
    grid: &rustial_engine::GeoGrid,
    coord: &rustial_math::GeoCoord,
    state: &MapState,
    params: &rustial_engine::ExtrusionParams,
) -> f32 {
    let terrain = state.elevation_at(coord).unwrap_or(0.0);
    match grid.altitude_mode {
        rustial_engine::AltitudeMode::ClampToGround => (terrain + params.base_meters) as f32,
        rustial_engine::AltitudeMode::RelativeToGround => {
            (terrain + grid.origin.alt + params.base_meters) as f32
        }
        rustial_engine::AltitudeMode::Absolute => (grid.origin.alt + params.base_meters) as f32,
    }
}

fn resolve_grid_surface_altitude(
    grid: &rustial_engine::GeoGrid,
    coord: &rustial_math::GeoCoord,
    state: &MapState,
) -> f64 {
    let terrain = state.elevation_at(coord).unwrap_or(0.0);
    match grid.altitude_mode {
        rustial_engine::AltitudeMode::ClampToGround => terrain,
        rustial_engine::AltitudeMode::RelativeToGround => terrain + grid.origin.alt,
        rustial_engine::AltitudeMode::Absolute => grid.origin.alt,
    }
}

fn build_unit_column_mesh() -> (Vec<ColumnVertex>, Vec<u32>) {
    let vertices = vec![
        // top
        ColumnVertex { position: [-0.5, -0.5, 1.0], normal: [0.0, 0.0, 1.0] },
        ColumnVertex { position: [0.5, -0.5, 1.0], normal: [0.0, 0.0, 1.0] },
        ColumnVertex { position: [-0.5, 0.5, 1.0], normal: [0.0, 0.0, 1.0] },
        ColumnVertex { position: [0.5, 0.5, 1.0], normal: [0.0, 0.0, 1.0] },
        // bottom
        ColumnVertex { position: [-0.5, -0.5, 0.0], normal: [0.0, 0.0, -1.0] },
        ColumnVertex { position: [0.5, -0.5, 0.0], normal: [0.0, 0.0, -1.0] },
        ColumnVertex { position: [-0.5, 0.5, 0.0], normal: [0.0, 0.0, -1.0] },
        ColumnVertex { position: [0.5, 0.5, 0.0], normal: [0.0, 0.0, -1.0] },
        // north
        ColumnVertex { position: [-0.5, -0.5, 0.0], normal: [0.0, -1.0, 0.0] },
        ColumnVertex { position: [0.5, -0.5, 0.0], normal: [0.0, -1.0, 0.0] },
        ColumnVertex { position: [-0.5, -0.5, 1.0], normal: [0.0, -1.0, 0.0] },
        ColumnVertex { position: [0.5, -0.5, 1.0], normal: [0.0, -1.0, 0.0] },
        // south
        ColumnVertex { position: [-0.5, 0.5, 1.0], normal: [0.0, 1.0, 0.0] },
        ColumnVertex { position: [0.5, 0.5, 1.0], normal: [0.0, 1.0, 0.0] },
        ColumnVertex { position: [-0.5, 0.5, 0.0], normal: [0.0, 1.0, 0.0] },
        ColumnVertex { position: [0.5, 0.5, 0.0], normal: [0.0, 1.0, 0.0] },
        // west
        ColumnVertex { position: [-0.5, -0.5, 0.0], normal: [-1.0, 0.0, 0.0] },
        ColumnVertex { position: [-0.5, -0.5, 1.0], normal: [-1.0, 0.0, 0.0] },
        ColumnVertex { position: [-0.5, 0.5, 0.0], normal: [-1.0, 0.0, 0.0] },
        ColumnVertex { position: [-0.5, 0.5, 1.0], normal: [-1.0, 0.0, 0.0] },
        // east
        ColumnVertex { position: [0.5, -0.5, 1.0], normal: [1.0, 0.0, 0.0] },
        ColumnVertex { position: [0.5, -0.5, 0.0], normal: [1.0, 0.0, 0.0] },
        ColumnVertex { position: [0.5, 0.5, 1.0], normal: [1.0, 0.0, 0.0] },
        ColumnVertex { position: [0.5, 0.5, 0.0], normal: [1.0, 0.0, 0.0] },
    ];
    let indices = vec![
        0, 2, 1, 1, 2, 3,
        4, 5, 6, 5, 7, 6,
        8, 10, 9, 9, 10, 11,
        12, 14, 13, 13, 14, 15,
        16, 18, 17, 17, 18, 19,
        20, 22, 21, 21, 22, 23,
    ];
    (vertices, indices)
}

fn build_column_instances(
    columns: &rustial_engine::ColumnInstanceSet,
    ramp: &rustial_engine::ColorRamp,
    state: &MapState,
    scene_origin: DVec3,
) -> Vec<ColumnInstanceData> {
    let (min_height, max_height) = column_height_range(columns);
    columns
        .columns
        .iter()
        .map(|column| {
            let projected = state.camera().projection().project(&column.position);
            let base_z = resolve_column_base_altitude(column, state);
            let normalized = if (max_height - min_height).abs() < f64::EPSILON {
                0.5
            } else {
                ((column.height - min_height) / (max_height - min_height)).clamp(0.0, 1.0)
            } as f32;
            let color = column.color.unwrap_or_else(|| ramp.evaluate(normalized));
            ColumnInstanceData {
                base_position: [
                    (projected.position.x - scene_origin.x) as f32,
                    (projected.position.y - scene_origin.y) as f32,
                    (base_z - scene_origin.z) as f32,
                ],
                dimensions: [column.width as f32, column.height as f32, 0.0, 0.0],
                color,
            }
        })
        .collect()
}

fn build_point_instances(
    points: &rustial_engine::PointInstanceSet,
    ramp: &rustial_engine::ColorRamp,
    state: &MapState,
    scene_origin: DVec3,
) -> Vec<ColumnInstanceData> {
    points
        .points
        .iter()
        .map(|point| {
            let projected = state.camera().projection().project(&point.position);
            let center_z = resolve_point_altitude(point, state);
            let diameter = (point.radius * 2.0) as f32;
            let color = point.color.unwrap_or_else(|| ramp.evaluate(point.intensity.clamp(0.0, 1.0)));
            ColumnInstanceData {
                base_position: [
                    (projected.position.x - scene_origin.x) as f32,
                    (projected.position.y - scene_origin.y) as f32,
                    (center_z - scene_origin.z - point.radius) as f32,
                ],
                dimensions: [diameter, diameter, 0.0, 0.0],
                color,
            }
        })
        .collect()
}

fn column_height_range(columns: &rustial_engine::ColumnInstanceSet) -> (f64, f64) {
    let mut min_height = f64::INFINITY;
    let mut max_height = f64::NEG_INFINITY;
    for column in &columns.columns {
        min_height = min_height.min(column.height);
        max_height = max_height.max(column.height);
    }
    if min_height.is_infinite() || max_height.is_infinite() {
        (0.0, 0.0)
    } else {
        (min_height, max_height)
    }
}

fn resolve_point_altitude(
    point: &rustial_engine::PointInstance,
    state: &MapState,
) -> f64 {
    let terrain = state.elevation_at(&point.position).unwrap_or(0.0);
    match point.altitude_mode {
        rustial_engine::AltitudeMode::ClampToGround => terrain,
        rustial_engine::AltitudeMode::RelativeToGround => terrain + point.position.alt,
        rustial_engine::AltitudeMode::Absolute => point.position.alt,
    }
}

fn resolve_column_base_altitude(
    column: &rustial_engine::ColumnInstance,
    state: &MapState,
) -> f64 {
    let terrain = state.elevation_at(&column.position).unwrap_or(0.0);
    match column.altitude_mode {
        rustial_engine::AltitudeMode::ClampToGround => terrain + column.base,
        rustial_engine::AltitudeMode::RelativeToGround => terrain + column.position.alt + column.base,
        rustial_engine::AltitudeMode::Absolute => column.position.alt + column.base,
    }
}

fn column_set_fingerprint(columns: &rustial_engine::ColumnInstanceSet) -> u64 {
    let mut h = columns.columns.len() as u64;
    for column in &columns.columns {
        h = h.wrapping_mul(31).wrapping_add(column.position.lat.to_bits());
        h = h.wrapping_mul(31).wrapping_add(column.position.lon.to_bits());
        h = h.wrapping_mul(31).wrapping_add(column.position.alt.to_bits());
        h = h.wrapping_mul(31).wrapping_add(column.height.to_bits());
        h = h.wrapping_mul(31).wrapping_add(column.base.to_bits());
        h = h.wrapping_mul(31).wrapping_add(column.width.to_bits());
        h = h.wrapping_mul(31).wrapping_add(column.pick_id);
        h = h.wrapping_mul(31).wrapping_add(match column.altitude_mode {
            rustial_engine::AltitudeMode::ClampToGround => 0,
            rustial_engine::AltitudeMode::RelativeToGround => 1,
            rustial_engine::AltitudeMode::Absolute => 2,
        });
        if let Some(color) = column.color {
            h = h.wrapping_mul(31).wrapping_add(color[0].to_bits() as u64);
            h = h.wrapping_mul(31).wrapping_add(color[1].to_bits() as u64);
            h = h.wrapping_mul(31).wrapping_add(color[2].to_bits() as u64);
            h = h.wrapping_mul(31).wrapping_add(color[3].to_bits() as u64);
        }
    }
    h
}

fn point_set_fingerprint(points: &rustial_engine::PointInstanceSet) -> u64 {
    let mut h = points.points.len() as u64;
    for point in &points.points {
        h = h.wrapping_mul(31).wrapping_add(point.position.lat.to_bits());
        h = h.wrapping_mul(31).wrapping_add(point.position.lon.to_bits());
        h = h.wrapping_mul(31).wrapping_add(point.position.alt.to_bits());
        h = h.wrapping_mul(31).wrapping_add(point.radius.to_bits());
        h = h.wrapping_mul(31).wrapping_add(point.intensity.to_bits() as u64);
        h = h.wrapping_mul(31).wrapping_add(point.pick_id);
        h = h.wrapping_mul(31).wrapping_add(match point.altitude_mode {
            rustial_engine::AltitudeMode::ClampToGround => 0,
            rustial_engine::AltitudeMode::RelativeToGround => 1,
            rustial_engine::AltitudeMode::Absolute => 2,
        });
        if let Some(color) = point.color {
            h = h.wrapping_mul(31).wrapping_add(color[0].to_bits() as u64);
            h = h.wrapping_mul(31).wrapping_add(color[1].to_bits() as u64);
            h = h.wrapping_mul(31).wrapping_add(color[2].to_bits() as u64);
            h = h.wrapping_mul(31).wrapping_add(color[3].to_bits() as u64);
        }
    }
    h
}

fn visualization_overlay_intersects_scene_viewport(
    overlay: &VisualizationOverlay,
    state: &MapState,
) -> bool {
    let scene_origin = state.scene_world_origin();
    let Some(bounds) = visualization_overlay_world_bounds(overlay, state, scene_origin) else {
        return false;
    };
    bounds.intersects(state.scene_viewport_bounds())
}

fn visualization_overlay_world_bounds(
    overlay: &VisualizationOverlay,
    state: &MapState,
    scene_origin: DVec3,
) -> Option<rustial_math::WorldBounds> {
    match overlay {
        VisualizationOverlay::GridScalar { grid, .. }
        | VisualizationOverlay::GridExtrusion { grid, .. } => Some(grid_world_bounds(grid, state, scene_origin)),
        VisualizationOverlay::Columns { columns, .. } => column_world_bounds(columns, state, scene_origin),
        VisualizationOverlay::Points { points, .. } => point_world_bounds(points, state, scene_origin),
    }
}

fn grid_world_bounds(
    grid: &rustial_engine::GeoGrid,
    state: &MapState,
    scene_origin: DVec3,
) -> rustial_math::WorldBounds {
    let corners = [
        grid_corner_coord(grid, 0, 0, state),
        grid_corner_coord(grid, 0, grid.cols, state),
        grid_corner_coord(grid, grid.rows, 0, state),
        grid_corner_coord(grid, grid.rows, grid.cols, state),
    ];
    let projected: Vec<_> = corners
        .iter()
        .map(|coord| state.camera().projection().project(coord))
        .collect();
    let mut bounds = rustial_math::WorldBounds::new(
        rustial_math::WorldCoord::new(
            projected[0].position.x - scene_origin.x,
            projected[0].position.y - scene_origin.y,
            projected[0].position.z - scene_origin.z,
        ),
        rustial_math::WorldCoord::new(
            projected[0].position.x - scene_origin.x,
            projected[0].position.y - scene_origin.y,
            projected[0].position.z - scene_origin.z,
        ),
    );
    for projected in projected.into_iter().skip(1) {
        bounds.extend_point(&rustial_math::WorldCoord::new(
            projected.position.x - scene_origin.x,
            projected.position.y - scene_origin.y,
            projected.position.z - scene_origin.z,
        ));
    }
    bounds
}

fn point_world_bounds(
    points: &rustial_engine::PointInstanceSet,
    state: &MapState,
    scene_origin: DVec3,
) -> Option<rustial_math::WorldBounds> {
    let mut bounds: Option<rustial_math::WorldBounds> = None;
    for point in &points.points {
        let projected = state.camera().projection().project(&point.position);
        let radius = point.radius;
        let center_z = resolve_point_altitude(point, state) - scene_origin.z;
        let point_bounds = rustial_math::WorldBounds::new(
            rustial_math::WorldCoord::new(
                projected.position.x - scene_origin.x - radius,
                projected.position.y - scene_origin.y - radius,
                center_z - radius,
            ),
            rustial_math::WorldCoord::new(
                projected.position.x - scene_origin.x + radius,
                projected.position.y - scene_origin.y + radius,
                center_z + radius,
            ),
        );
        if let Some(existing) = bounds.as_mut() {
            existing.extend(&point_bounds);
        } else {
            bounds = Some(point_bounds);
        }
    }
    bounds
}

fn column_world_bounds(
    columns: &rustial_engine::ColumnInstanceSet,
    state: &MapState,
    scene_origin: DVec3,
) -> Option<rustial_math::WorldBounds> {
    let mut bounds: Option<rustial_math::WorldBounds> = None;
    for column in &columns.columns {
        let projected = state.camera().projection().project(&column.position);
        let base_z = resolve_column_base_altitude(column, state) - scene_origin.z;
        let half_width = column.width * 0.5;
        let column_bounds = rustial_math::WorldBounds::new(
            rustial_math::WorldCoord::new(
                projected.position.x - scene_origin.x - half_width,
                projected.position.y - scene_origin.y - half_width,
                base_z,
            ),
            rustial_math::WorldCoord::new(
                projected.position.x - scene_origin.x + half_width,
                projected.position.y - scene_origin.y + half_width,
                base_z + column.height,
            ),
        );
        if let Some(existing) = bounds.as_mut() {
            existing.extend(&column_bounds);
        } else {
            bounds = Some(column_bounds);
        }
    }
    bounds
}

fn build_shared_terrain_grid(resolution: usize) -> (Vec<TerrainGridVertex>, Vec<u32>) {
    let res = resolution.max(2);
    let mut vertices = Vec::with_capacity(res * res);
    let mut indices = Vec::with_capacity((res - 1) * (res - 1) * 6);

    for row in 0..res {
        for col in 0..res {
            let u = col as f32 / (res - 1) as f32;
            let v = row as f32 / (res - 1) as f32;
            vertices.push(TerrainGridVertex { uv: [u, v], skirt: 0.0 });
        }
    }

    for row in 0..(res - 1) {
        for col in 0..(res - 1) {
            let tl = (row * res + col) as u32;
            let tr = tl + 1;
            let bl = ((row + 1) * res + col) as u32;
            let br = bl + 1;
            indices.extend_from_slice(&[tl, bl, tr, tr, bl, br]);
        }
    }

    let edges: [Vec<usize>; 4] = [
        (0..res).collect(),
        ((res - 1) * res..res * res).collect(),
        (0..res).map(|r| r * res).collect(),
        (0..res).map(|r| r * res + res - 1).collect(),
    ];

    for edge in &edges {
        for i in 0..edge.len() - 1 {
            let a = edge[i] as u32;
            let b = edge[i + 1] as u32;
            let uv_a = vertices[edge[i]].uv;
            let uv_b = vertices[edge[i + 1]].uv;
            let base_a = vertices.len() as u32;
            let base_b = base_a + 1;
            vertices.push(TerrainGridVertex { uv: uv_a, skirt: 1.0 });
            vertices.push(TerrainGridVertex { uv: uv_b, skirt: 1.0 });
            indices.extend_from_slice(&[a, base_a, b, b, base_a, base_b]);
        }
    }

    (vertices, indices)
}

fn build_terrain_tile_uniform(
    mesh: &TerrainMeshData,
    elevation: &rustial_engine::TerrainElevationTexture,
    state: &MapState,
    scene_origin: DVec3,
) -> TerrainTileUniform {
    let nw = rustial_math::tile_to_geo(&mesh.tile);
    let se = rustial_math::tile_xy_to_geo(
        mesh.tile.zoom,
        mesh.tile.x as f64 + 1.0,
        mesh.tile.y as f64 + 1.0,
    );
    let projection_kind = match state.camera().projection() {
        rustial_engine::CameraProjection::WebMercator => 0.0,
        rustial_engine::CameraProjection::Equirectangular => 1.0,
        _ => 0.0,
    };
    let skirt = rustial_engine::skirt_height(
        mesh.tile.zoom,
        mesh.vertical_exaggeration as f64,
    ) as f32;
    let skirt_base = (elevation.min_elev * mesh.vertical_exaggeration - skirt)
        .max(-skirt * 3.0);
    let elev_region = if mesh.tile != mesh.elevation_source_tile {
        rustial_engine::elevation_region_in_texture_space(
            mesh.elevation_region,
            elevation.width,
            elevation.height,
        )
    } else {
        mesh.elevation_region
    };
    TerrainTileUniform {
        geo_bounds: [nw.lat as f32, nw.lon as f32, se.lat as f32, se.lon as f32],
        scene_origin: [
            scene_origin.x as f32,
            scene_origin.y as f32,
            scene_origin.z as f32,
            projection_kind,
        ],
        elev_params: [
            mesh.vertical_exaggeration,
            skirt_base,
            elevation.min_elev,
            elevation.max_elev,
        ],
        elev_region: [
            elev_region.u_min,
            elev_region.v_min,
            elev_region.u_max,
            elev_region.v_max,
        ],
    }
}

fn build_model_vertices(mesh: &rustial_engine::ModelMesh) -> Vec<ModelVertex> {
    debug_assert_eq!(mesh.positions.len(), mesh.normals.len());
    debug_assert_eq!(mesh.positions.len(), mesh.uvs.len());

    mesh.positions
        .iter()
        .zip(mesh.normals.iter())
        .zip(mesh.uvs.iter())
        .map(|((pos, normal), uv)| ModelVertex {
            position: *pos,
            normal: *normal,
            uv: *uv,
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustial_engine::{ColorRamp, ColorStop, ColumnInstance, ColumnInstanceSet, GeoCoord, GeoGrid, VisualizationOverlay};

    fn visible_tile_with_fade(fade_opacity: f32) -> VisibleTile {
        let id = TileId::new(3, 4, 2);
        VisibleTile {
            target: id,
            actual: id,
            data: None,
            fade_opacity,
        }
    }

    fn test_ramp() -> ColorRamp {
        ColorRamp::new(vec![
            ColorStop { value: 0.0, color: [0.0, 0.0, 1.0, 0.5] },
            ColorStop { value: 1.0, color: [1.0, 0.0, 0.0, 0.8] },
        ])
    }

    #[test]
    fn tile_batch_cache_key_changes_when_fade_opacity_changes() {
        let a = [visible_tile_with_fade(0.25)];
        let b = [visible_tile_with_fade(0.75)];

        let key_a = TileBatchCacheKey::new(&a, DVec3::ZERO, rustial_engine::CameraProjection::WebMercator);
        let key_b = TileBatchCacheKey::new(&b, DVec3::ZERO, rustial_engine::CameraProjection::WebMercator);

        assert_ne!(key_a, key_b, "tile batch cache key must include fade-sensitive inputs");
    }

    #[test]
    fn tile_batch_cache_key_stays_equal_when_fade_opacity_matches() {
        let a = [visible_tile_with_fade(1.0)];
        let b = [visible_tile_with_fade(1.0)];

        let key_a = TileBatchCacheKey::new(&a, DVec3::ZERO, rustial_engine::CameraProjection::WebMercator);
        let key_b = TileBatchCacheKey::new(&b, DVec3::ZERO, rustial_engine::CameraProjection::WebMercator);

        assert_eq!(key_a, key_b);
    }

    #[test]
    fn diff_column_instance_ranges_tracks_contiguous_changes() {
        let old = vec![
            ColumnInstanceData {
                base_position: [0.0, 0.0, 0.0],
                dimensions: [1.0, 2.0, 0.0, 0.0],
                color: [1.0, 0.0, 0.0, 1.0],
            },
            ColumnInstanceData {
                base_position: [1.0, 0.0, 0.0],
                dimensions: [1.0, 2.0, 0.0, 0.0],
                color: [0.0, 1.0, 0.0, 1.0],
            },
            ColumnInstanceData {
                base_position: [2.0, 0.0, 0.0],
                dimensions: [1.0, 2.0, 0.0, 0.0],
                color: [0.0, 0.0, 1.0, 1.0],
            },
            ColumnInstanceData {
                base_position: [3.0, 0.0, 0.0],
                dimensions: [1.0, 2.0, 0.0, 0.0],
                color: [1.0, 1.0, 0.0, 1.0],
            },
        ];
        let mut new = old.clone();
        new[1].dimensions[1] = 4.0;
        new[2].color = [1.0, 0.0, 1.0, 1.0];

        assert_eq!(diff_column_instance_ranges(&old, &new), vec![1..3]);
    }

    #[test]
    fn diff_column_instance_ranges_splits_disjoint_changes() {
        let old = vec![
            ColumnInstanceData {
                base_position: [0.0, 0.0, 0.0],
                dimensions: [1.0, 2.0, 0.0, 0.0],
                color: [1.0, 0.0, 0.0, 1.0],
            },
            ColumnInstanceData {
                base_position: [1.0, 0.0, 0.0],
                dimensions: [1.0, 2.0, 0.0, 0.0],
                color: [0.0, 1.0, 0.0, 1.0],
            },
            ColumnInstanceData {
                base_position: [2.0, 0.0, 0.0],
                dimensions: [1.0, 2.0, 0.0, 0.0],
                color: [0.0, 0.0, 1.0, 1.0],
            },
        ];
        let mut new = old.clone();
        new[0].dimensions[0] = 3.0;
        new[2].base_position[2] = 5.0;

        assert_eq!(diff_column_instance_ranges(&old, &new), vec![0..1, 2..3]);
    }

    #[test]
    fn visualization_overlay_visibility_rejects_far_grid() {
        let mut state = MapState::new();
        state.set_viewport(1280, 720);
        state.set_camera_target(GeoCoord::from_lat_lon(0.0, 0.0));
        state.set_camera_distance(1_000.0);
        state.update_camera(1.0 / 60.0);

        let overlay = VisualizationOverlay::GridScalar {
            layer_id: LayerId::next(),
            grid: GeoGrid::new(GeoCoord::from_lat_lon(70.0, 120.0), 2, 2, 50.0, 50.0),
            field: rustial_engine::ScalarField2D::from_data(2, 2, vec![1.0; 4]),
            ramp: test_ramp(),
        };

        assert!(!visualization_overlay_intersects_scene_viewport(&overlay, &state));
    }

    #[test]
    fn visualization_overlay_visibility_accepts_near_columns() {
        let mut state = MapState::new();
        state.set_viewport(1280, 720);
        state.set_camera_target(GeoCoord::from_lat_lon(0.0, 0.0));
        state.set_camera_distance(1_000.0);
        state.update_camera(1.0 / 60.0);

        let overlay = VisualizationOverlay::Columns {
            layer_id: LayerId::next(),
            columns: ColumnInstanceSet::new(vec![
                ColumnInstance::new(GeoCoord::from_lat_lon(0.0, 0.0), 10.0, 5.0),
            ]),
            ramp: test_ramp(),
        };

        assert!(visualization_overlay_intersects_scene_viewport(&overlay, &state));
    }
}