viewport-lib 0.18.3

3D viewport rendering library
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
//! `ViewportRenderer` : the main entry point for the viewport library.
//!
//! Wraps [`ViewportGpuResources`] and provides `prepare()` / `paint()` methods
//! that take raw `wgpu` types. GUI framework adapters (e.g. the egui
//! `CallbackTrait` impl in the application crate) delegate to these methods.

#[macro_use]
mod types;
mod indirect;
mod instancing_state;
use instancing_state::InstancingState;
mod per_object_state;
use per_object_state::PerObjectState;
mod shadow_state;
use shadow_state::ShadowState;
mod paths;
pub use paths::{OwnedPath, PassPath, PassView};
mod picking;
pub use picking::PickRectResult;
mod point_shadow_pool;
mod prepare;
mod render;
pub mod shader_hashes;
mod shadow_debug_stats;
mod shadows;
pub mod stats;
pub use shadow_debug_stats::ShadowDebugStats;

#[cfg(test)]
mod hidden_tests;
#[cfg(test)]
mod lod_instance_tests;

pub use self::types::{
    AnimTrack, AtlasViewerCorner, BorderMode, CameraFrame, ClipObject, ClipShape,
    ComputeFilterItem, ComputeFilterKind, CylindricalFacing, DebugOutputMode, DebugQuantity,
    DebugVis, DecalAnimation, DecalBlendMode, DecalItem, DecalProjection, EffectsFrame,
    EmitterConfig, EnvironmentMap, FilterMode, ForceField, FrameData, GaussianSplatData,
    GaussianSplatId, GaussianSplatItem, GlyphItem, GlyphSetRefItem, GlyphType,
    GpuParticleSystemItem, GradientStop, GroundPlane, GroundPlaneMode, ImageAnchor, ImageSliceItem,
    InteractionFrame, LabelAnchor, LabelItem, LerpAnim, LicOverlay, LightKind, LightSource,
    LightingSettings, LineCap, LineJoin, LoadingBarAnchor, LoadingBarItem, MAX_POINT_SHADOW_LIGHTS,
    MeshInstanceItem, NineSlice, OVERLAY_MAX_GRADIENT_STOPS, OverlayAnimation, OverlayAnimations,
    OverlayEasing, OverlayFill, OverlayFrame, OverlayImageItem, OverlayPolylineItem,
    OverlayRectItem, OverlayShape, OverlayShapeItem, OverlayTextureId, POINT_SHADOW_FACE_SIZE,
    ParticleMeshAlign, PathTrack, PickId, PointCloudItem, PointCloudRefItem, PointRenderMode,
    PointShadowMode, PolylineItem, PolylineRefItem, PostProcessSettings, RenderCamera, RepeatMode,
    RibbonItem, RibbonRefItem, RulerItem, ScalarBarAnchor, ScalarBarItem, ScalarBarOrientation,
    ScatterQuality, ScatterSettings, ScatterVolumeItem, SceneEffects, SceneFrame, SceneRenderItem,
    ScreenImageItem, ShDegree, ShadowFilter, SliceAxis, SpawnShape, SpriteBlend,
    SpriteInstanceSetRefItem, SpriteItem, SpriteLitParams, SpriteNormalMode, SpriteOrientation,
    SpriteSetRefItem, SpriteSizeMode, StreamtubeItem, StreamtubeRefItem, SurfaceLICConfig,
    SurfaceSubmission, TensorGlyphItem, TensorGlyphSetRefItem, TextureTransform, TileMode,
    ToneMapping, TriangleDirection, TubeItem, TubeRefItem, VelocityDist, ViewportEffects,
    ViewportFrame, VolumeItem, VolumeMeshItem, VolumeSurfaceSliceItem, VolumeTransparency,
    aabb_wireframe_polyline, sphere_wireframe_polyline,
};

/// An opaque handle to a per-viewport GPU state slot.
///
/// Obtained from [`ViewportRenderer::create_viewport`] and passed to
/// [`ViewportRenderer::prepare_viewport`], [`ViewportRenderer::paint_viewport`],
/// and [`ViewportRenderer::render_viewport`].
///
/// The slot index is managed internally. To bind a `ViewportId` to a camera frame,
/// use [`CameraFrame::with_viewport_id`]. Single-viewport applications that use
/// the legacy [`ViewportRenderer::prepare`] / [`ViewportRenderer::paint`] API do
/// not need this type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ViewportId(pub(crate) usize);

use self::shadows::{compute_cascade_matrix, compute_cascade_splits};
use self::types::{INSTANCING_THRESHOLD, InstancedBatch};
use crate::resources::{
    BatchMeta, CLIP_VOLUME_MAX, CameraUniform, ClipPlanesUniform, ClipVolumeEntry,
    ClipVolumesUniform, GridUniform, InstanceAabb, InstanceData, LightsUniform, ObjectUniform,
    OutlineEdgeUniform, OutlineObjectBuffers, OutlineUniform, PickInstance, ShadowAtlasUniform,
    SingleLightUniform, SplatOutlineMaskUniform, ViewportGpuResources,
};

/// Per-viewport GPU state: uniform buffers and bind groups that differ per viewport.
///
/// Each viewport slot owns its own camera, clip planes, clip volume, shadow info,
/// and grid buffers, plus the bind groups that reference them. Scene-global
/// resources (lights, shadow atlas texture, IBL) are shared via the bind group
/// pointing to buffers on `ViewportGpuResources`.
pub(crate) struct ViewportSlot {
    pub camera_buf: wgpu::Buffer,
    pub clip_planes_buf: wgpu::Buffer,
    pub clip_volume_buf: wgpu::Buffer,
    pub shadow_info_buf: wgpu::Buffer,
    pub grid_buf: wgpu::Buffer,
    /// Camera bind group (group 0) referencing this slot's per-viewport buffers
    /// plus shared scene-global resources.
    pub camera_bind_group: wgpu::BindGroup,
    /// Grid bind group (group 0 for grid pipeline) referencing this slot's grid buffer.
    pub grid_bind_group: wgpu::BindGroup,
    /// Per-viewport HDR post-process render targets.
    ///
    /// Created lazily on first HDR render call and resized when viewport dimensions change.
    pub hdr: Option<crate::resources::ViewportHdrState>,
    /// Per-fragment debug storage buffer (group 0 binding 12). Allocated at
    /// `width * height * 16` bytes when debug_vis is active; None otherwise.
    pub debug_frag_buf: Option<wgpu::Buffer>,
    /// Viewport dimensions for which `debug_frag_buf` was allocated.
    pub debug_frag_dims: (u32, u32),

    // --- Per-viewport interaction state ---
    /// Per-frame outline buffers for selected objects, rebuilt in prepare().
    pub outline_object_buffers: Vec<OutlineObjectBuffers>,
    /// Per-frame outline buffers for selected Gaussian splat sets, rebuilt in prepare().
    pub splat_outline_buffers: Vec<crate::resources::SplatOutlineBuffers>,
    /// Indices into `volume_gpu_data` for selected volumes, rebuilt in prepare().
    pub volume_outline_indices: Vec<usize>,
    /// Indices into `glyph_gpu_data` for selected glyph sets, rebuilt in prepare().
    /// Each entry is (gpu_data_index, instance_filter): None draws all instances,
    /// Some(indices) draws only those specific instance indices.
    pub glyph_outline_indices: Vec<(usize, Option<Vec<u32>>)>,
    /// Indices into `tensor_glyph_gpu_data` for selected tensor glyph sets, rebuilt in prepare().
    pub tensor_glyph_outline_indices: Vec<(usize, Option<Vec<u32>>)>,
    /// Indices into `sprite_gpu_data` for selected sprite sets, rebuilt in prepare().
    pub sprite_outline_indices: Vec<(usize, Option<Vec<u32>>)>,
    /// Per-frame inline quad outline buffers for selected image slices, rebuilt in prepare().
    pub raw_geom_outline_buffers: Vec<crate::resources::RawGeomOutlineBuffers>,
    /// Per-frame NDC rect outline buffers for selected screen images, rebuilt in prepare().
    pub screen_rect_outline_buffers: Vec<crate::resources::ScreenRectOutlineBuffers>,
    /// Indices into `implicit_gpu_data` for selected GPU implicit items, rebuilt in prepare().
    pub implicit_outline_indices: Vec<usize>,
    /// Per-frame outline data for selected GPU marching cubes jobs, rebuilt in prepare().
    pub mc_outline_data: Vec<crate::resources::gpu_marching_cubes::McOutlineItem>,
    /// Outline items for selected streamtubes (index into streamtube_gpu_data + mask bind group).
    pub streamtube_outline_items: Vec<crate::resources::CurveMeshOutlineItem>,
    /// Outline items for selected tubes.
    pub tube_outline_items: Vec<crate::resources::CurveMeshOutlineItem>,
    /// Outline items for selected ribbons.
    pub ribbon_outline_items: Vec<crate::resources::CurveMeshOutlineItem>,
    /// Indices into polyline_gpu_data for selected user polylines.
    pub polyline_outline_indices: Vec<usize>,
    /// Per-frame x-ray buffers for selected objects, rebuilt in prepare().
    pub xray_object_buffers: Vec<(
        crate::resources::mesh_store::MeshId,
        wgpu::Buffer,
        wgpu::BindGroup,
    )>,
    /// Per-frame constraint guide line buffers, rebuilt in prepare().
    pub constraint_line_buffers: Vec<(
        wgpu::Buffer,
        wgpu::Buffer,
        u32,
        wgpu::Buffer,
        wgpu::BindGroup,
    )>,
    /// Per-frame cap geometry buffers (section view cross-section fill), rebuilt in prepare().
    pub cap_buffers: Vec<(
        wgpu::Buffer,
        wgpu::Buffer,
        u32,
        wgpu::Buffer,
        wgpu::BindGroup,
    )>,
    /// Per-frame clip plane fill overlay buffers, rebuilt in prepare().
    pub clip_plane_fill_buffers: Vec<(
        wgpu::Buffer,
        wgpu::Buffer,
        u32,
        wgpu::Buffer,
        wgpu::BindGroup,
    )>,
    /// Per-frame clip plane line overlay buffers, rebuilt in prepare().
    pub clip_plane_line_buffers: Vec<(
        wgpu::Buffer,
        wgpu::Buffer,
        u32,
        wgpu::Buffer,
        wgpu::BindGroup,
    )>,
    /// Vertex buffer for axes indicator geometry (rebuilt each frame).
    pub axes_vertex_buffer: wgpu::Buffer,
    /// Number of vertices in the axes indicator buffer.
    pub axes_vertex_count: u32,
    /// Gizmo model-matrix uniform buffer.
    pub gizmo_uniform_buf: wgpu::Buffer,
    /// Gizmo bind group (group 1: model matrix uniform).
    pub gizmo_bind_group: wgpu::BindGroup,
    /// Gizmo vertex buffer.
    pub gizmo_vertex_buffer: wgpu::Buffer,
    /// Gizmo index buffer.
    pub gizmo_index_buffer: wgpu::Buffer,
    /// Number of indices in the current gizmo mesh.
    pub gizmo_index_count: u32,

    // --- Sub-object highlight (per-viewport, generation-cached) ---
    /// Per-viewport dynamic resolution intermediate render target.
    /// `None` when render_scale == 1.0 or not yet initialised.
    pub dyn_res: Option<crate::resources::dyn_res::DynResTarget>,
    /// Per-viewport intermediate render target for the HDR eframe callback path.
    /// `None` until the first `prepare_hdr_callback` call for this viewport.
    pub hdr_callback: Option<crate::resources::dyn_res::HdrCallbackTarget>,
    /// Cached GPU data for sub-object highlight rendering.
    /// `None` when no sub-object selection is active and no volumes are selected.
    pub sub_highlight: Option<crate::resources::SubHighlightGpuData>,
    /// Version of the last sub-selection snapshot that was uploaded.
    /// `u64::MAX` forces a rebuild on the first frame.
    pub sub_highlight_generation: u64,
}

impl ViewportSlot {
    /// Draw the axes orientation indicator into an already-begun render pass.
    ///
    /// Shared by the LDR and HDR paths; both draw it last in screen space so it
    /// sits on top. Does nothing when the indicator is disabled or empty.
    pub(crate) fn draw_axes_indicator(
        &self,
        render_pass: &mut wgpu::RenderPass<'_>,
        resources: &ViewportGpuResources,
        show_axes_indicator: bool,
    ) {
        if show_axes_indicator && self.axes_vertex_count > 0 {
            render_pass.set_pipeline(&resources.axes_pipeline);
            render_pass.set_vertex_buffer(0, self.axes_vertex_buffer.slice(..));
            render_pass.draw(0..self.axes_vertex_count, 0..1);
        }
    }
}

/// Retained pick state for one GPU implicit surface, built during `prepare()`.
struct GpuImplicitPickItem {
    id: u64,
    primitives: Vec<crate::resources::ImplicitPrimitive>,
    blend_mode: crate::resources::ImplicitBlendMode,
    max_steps: u32,
    step_scale: f32,
    hit_threshold: f32,
    max_distance: f32,
}

/// Retained pick state for one GPU marching cubes job, built during `prepare()`.
struct GpuMcPickItem {
    id: u64,
    isovalue: f32,
    volume_data: std::sync::Arc<crate::geometry::marching_cubes::VolumeData>,
}

/// Renderer wrapping all GPU resources and providing `prepare()` and `paint()` methods.
/// Per-viewport scene-colour resolve sampled by the refractive sprite pass.
///
/// Lazily allocated on the first frame containing a refractive sprite; resized
/// whenever the HDR target dimensions change. The bind group is rebuilt with
/// the resolve when either changes.
struct SpriteRefractionResolve {
    texture: wgpu::Texture,
    view: wgpu::TextureView,
    size: [u32; 2],
}

/// GPU timestamp slot for the main opaque HDR scene pass.
pub(crate) const GPU_TS_SCENE: u32 = 0;
/// GPU timestamp slot for the directional shadow depth pass.
pub(crate) const GPU_TS_SHADOW: u32 = 1;
/// GPU timestamp slot for the OIT accumulation pass.
pub(crate) const GPU_TS_OIT: u32 = 2;
/// GPU timestamp slot for the tone-map / resolve pass.
pub(crate) const GPU_TS_POST: u32 = 3;
/// GPU timestamp slot for the main-camera GPU cull dispatch (the
/// `cull_instances` + `write_indirect_args` compute passes). Only the main
/// camera cull is timed; shadow-cascade and single-mesh culls are not.
pub(crate) const GPU_TS_CULL: u32 = 4;
/// Number of measured GPU passes; the query set holds `2 * GPU_TS_SLOTS` entries
/// (a begin/end pair per slot).
pub(crate) const GPU_TS_SLOTS: u32 = 5;

/// Owns the GPU pipelines and per-frame state for rendering a scene. Call
/// `prepare` once per frame to upload data, then `paint_to` (or `render`) to
/// issue draw calls.
pub struct ViewportRenderer {
    resources: ViewportGpuResources,
    /// State for the instanced (GPU-driven) mesh draw path.
    instancing: InstancingState,
    /// Registered item-type plugins keyed by
    /// [`ItemTypePlugin::type_name`](crate::plugin_api::ItemTypePlugin::type_name).
    /// `init_gpu` is invoked once on registration; per-frame `prepare` and
    /// `paint` fire when a matching collection is on `SceneFrame`.
    item_type_plugins:
        std::collections::HashMap<&'static str, Box<dyn crate::plugin_api::ItemTypePlugin>>,
    /// Monotonic frame counter passed to plugin contexts.
    plugin_frame_index: u64,
    /// Performance counters from the last frame.
    last_stats: crate::renderer::stats::FrameStats,
    /// Per-frame point cloud GPU data, rebuilt in prepare(), consumed in paint().
    point_cloud_gpu_data: Vec<crate::resources::PointCloudGpuData>,
    /// Per-frame glyph GPU data, rebuilt in prepare(), consumed in paint().
    glyph_gpu_data: Vec<crate::resources::GlyphGpuData>,
    /// Per-frame tensor glyph GPU data, rebuilt in prepare(), consumed in paint().
    tensor_glyph_gpu_data: Vec<crate::resources::TensorGlyphGpuData>,
    /// Per-frame polyline GPU data, rebuilt in prepare(), consumed in paint().
    polyline_gpu_data: Vec<crate::resources::PolylineGpuData>,
    /// Per-frame volume GPU data, rebuilt in prepare(), consumed in paint().
    volume_gpu_data: Vec<crate::resources::VolumeGpuData>,
    /// Per-frame streamtube GPU data, rebuilt in prepare(), consumed in paint().
    streamtube_gpu_data: Vec<crate::resources::StreamtubeGpuData>,
    /// Per-frame general tube GPU data, rebuilt in prepare(), consumed in paint().
    tube_gpu_data: Vec<crate::resources::StreamtubeGpuData>,
    /// Per-frame ribbon GPU data, rebuilt in prepare(), consumed in paint().
    ribbon_gpu_data: Vec<crate::resources::StreamtubeGpuData>,
    /// Indices into streamtube_gpu_data for selected streamtubes (set in prepare_scene, consumed in prepare_viewport).
    streamtube_selected_gpu_indices: Vec<usize>,
    /// Indices into tube_gpu_data for selected tubes (set in prepare_scene, consumed in prepare_viewport).
    tube_selected_gpu_indices: Vec<usize>,
    /// Indices into ribbon_gpu_data for selected ribbons (set in prepare_scene, consumed in prepare_viewport).
    ribbon_selected_gpu_indices: Vec<usize>,
    /// Indices into polyline_gpu_data for selected user polylines (set in prepare_scene, consumed in prepare_viewport).
    polyline_selected_gpu_indices: Vec<usize>,
    /// Per-frame image slice GPU data, rebuilt in prepare(), consumed in paint().
    image_slice_gpu_data: Vec<crate::resources::ImageSliceGpuData>,
    /// Per-frame volume surface slice GPU data, rebuilt in prepare(), consumed in paint().
    volume_surface_slice_gpu_data: Vec<crate::resources::VolumeSurfaceSliceGpuData>,
    /// Per-frame Surface LIC GPU data, rebuilt in prepare(), consumed in paint().
    lic_gpu_data: Vec<crate::resources::LicSurfaceGpuData>,
    /// Per-frame GPU implicit surface data, rebuilt in prepare(), consumed in paint().
    implicit_gpu_data: Vec<crate::resources::implicit::ImplicitGpuItem>,
    /// Per-frame decal GPU data, rebuilt in prepare(), consumed in paint() (D1).
    decal_gpu_data: Vec<crate::resources::decal::DecalGpuItem>,
    /// Per-frame decal exclude GPU data, rebuilt in prepare(), consumed in paint() (D5).
    decal_exclude_items: Vec<crate::resources::decal::DecalExcludeGpuItem>,
    /// Per-frame GPU marching cubes render data, rebuilt in prepare(), consumed in paint().
    mc_gpu_data: Vec<crate::resources::gpu_marching_cubes::McFrameData>,
    /// Per-frame sprite GPU data, rebuilt in prepare(), consumed in paint().
    sprite_gpu_data: Vec<crate::resources::SpriteGpuData>,
    /// Per-frame mesh-instance batches, rebuilt in prepare(), consumed in paint().
    mesh_instance_gpu_data: Vec<crate::resources::MeshInstanceGpuData>,
    /// Per-frame GPU particle systems, dispatched in prepare(), consumed in paint().
    particle_gpu_data: Vec<crate::resources::gpu_particles::ParticleFrameData>,
    /// Scene-colour resolve textures for the refractive sprite pass, indexed
    /// alongside `viewport_slots`. Lazily allocated when the first refractive
    /// sprite appears for a viewport.
    sprite_refraction_resolves: Vec<Option<SpriteRefractionResolve>>,
    /// Per-frame Gaussian splat draw data, rebuilt in prepare_viewport_internal(), consumed in paint().
    gaussian_splat_draw_data: Vec<crate::resources::GaussianSplatDrawData>,
    /// Per-frame screen-image GPU data, rebuilt in prepare(), consumed in paint().
    screen_image_gpu_data: Vec<crate::resources::ScreenImageGpuData>,
    /// Per-frame overlay image GPU data, rebuilt in prepare(), consumed in paint().
    overlay_image_gpu_data: Vec<crate::resources::ScreenImageGpuData>,
    /// Per-frame overlay label GPU data, rebuilt in prepare(), consumed in paint().
    label_gpu_data: Option<crate::resources::LabelGpuData>,
    /// Per-frame scalar bar GPU data, rebuilt in prepare(), consumed in paint().
    scalar_bar_gpu_data: Option<crate::resources::LabelGpuData>,
    /// Per-frame ruler GPU data, rebuilt in prepare(), consumed in paint().
    ruler_gpu_data: Option<crate::resources::LabelGpuData>,
    /// Per-frame loading bar GPU data, rebuilt in prepare(), consumed in paint().
    loading_bar_gpu_data: Option<crate::resources::LabelGpuData>,
    /// Per-frame overlay rect GPU data, rebuilt in prepare(), consumed in paint().
    overlay_rect_gpu_data: Option<crate::resources::LabelGpuData>,
    /// Per-frame SDF overlay shape GPU data, rebuilt in prepare(), consumed in paint().
    overlay_shape_gpu_data: Option<crate::resources::OverlayShapeGpuData>,
    /// Cached GPU textures for the backdrop blur effect (frosted glass).
    /// Recreated when the viewport size changes.
    backdrop_blur_state: Option<crate::resources::BackdropBlurState>,
    /// Per-viewport GPU state slots.
    ///
    /// Indexed by `FrameData::camera.viewport_index`. Each slot owns independent
    /// uniform buffers and bind groups for camera, clip planes, clip volume,
    /// shadow info, and grid. Slots are grown lazily in `prepare` via
    /// `ensure_viewport_slot`. There are at most 4 in the current UI.
    viewport_slots: Vec<ViewportSlot>,
    /// GPU compute filter results from the last `prepare()` call.
    ///
    /// Each entry contains a compacted index buffer + count for one filtered mesh.
    /// Consumed during `paint()` to override the mesh's default index buffer.
    /// Cleared and rebuilt each frame.
    compute_filter_results: Vec<crate::resources::ComputeFilterResult>,
    /// State for the non-instanced (per-object) mesh draw path.
    mesh_uniforms: PerObjectState,
    /// Cached shadow state carried across frames.
    shadow: ShadowState,
    /// Current runtime mode controlling internal default behavior.
    runtime_mode: crate::renderer::stats::RuntimeMode,
    /// Optional cap on how much main-thread time `prepare` is allowed to
    /// spend running apply closures for completed upload jobs.
    ///
    /// `None` means unbounded (apply work runs to completion in one
    /// frame). `Some(d)` spreads the cost across frames so heavy
    /// completions do not produce one fat frame; the deferred applies
    /// run on the next call to `prepare`.
    upload_budget: Option<std::time::Duration>,
    /// Active performance policy: target FPS, render scale bounds, and permitted reductions.
    performance_policy: crate::renderer::stats::PerformancePolicy,
    /// Current render scale tracked by the adaptation controller (or set manually).
    ///
    /// Clamped to `[policy.min_render_scale, policy.max_render_scale]`.
    /// Reported in `FrameStats::render_scale` each frame.
    current_render_scale: f32,
    /// Instant the renderer was constructed. Used as the t=0 reference for
    /// per-frame animated effects (e.g. `ScatterVolume::noise` time scrolling).
    start_instant: std::time::Instant,
    /// Instant recorded at the start of the most recent `prepare()` call.
    /// Used to compute `total_frame_ms` on the following frame.
    last_prepare_instant: Option<std::time::Instant>,
    /// Frame counter incremented each `prepare()` call. Used for picking throttle in Playback mode.
    frame_counter: u64,
    /// Current LOD level per item, keyed by pick id, carried across frames so
    /// level switches use hysteresis. Items without a pick id are not tracked
    /// here and resolve fresh each frame. Pruned to the items seen each frame.
    lod_levels: std::collections::HashMap<u64, usize>,
    /// Current LOD level per mesh instance, keyed by `(item pick id, instance
    /// index)`. Same role as `lod_levels` but for `MeshInstanceItem`, where each
    /// instance picks its own level. Instances in items without a pick id are
    /// not tracked. Pruned to the instances seen each frame.
    mesh_instance_lod_levels: std::collections::HashMap<(u64, u32), usize>,
    /// Surface items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_scene_items: Vec<SceneRenderItem>,
    /// Point cloud items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_point_cloud_items: Vec<PointCloudItem>,
    /// Gaussian splat items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_splat_items: Vec<GaussianSplatItem>,
    /// Volume items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_volume_items: Vec<VolumeItem>,
    /// Scatter volume items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_scatter_volume_items: Vec<crate::renderer::types::ScatterVolumeItem>,
    /// Volumes packed into the GPU storage buffer this frame
    /// (volume, density_multiplier, flag bits). Stored so `render_viewport`
    /// can re-upload as needed without re-walking the scene frame.
    pub(crate) prepared_scatter_volumes:
        Vec<(crate::scene::scatter_volume::ScatterVolume, f32, u32)>,
    /// Subset of the prepared scatter volumes that carry `RefractionParams`.
    /// Cleared and refilled each frame by `prepare_viewport`. The refraction
    /// pass walks this list; an empty list skips the pass entirely.
    pub(crate) prepared_refraction_volumes: Vec<(crate::scene::scatter_volume::ScatterVolume, f32)>,
    /// Per-viewport scatter intermediates and temporal history. Indexed by
    /// `vp_idx`. Grown lazily inside the scatter pass; each entry is
    /// reallocated when the requested scatter target size or downsample mode
    /// changes.
    pub(crate) scatter_viewport_states: Vec<Option<crate::resources::ScatterViewportState>>,
    /// Opaque volume mesh items from the last `prepare()` call, retained for cell-level `pick()` dispatch.
    pick_volume_mesh_items: Vec<VolumeMeshItem>,
    /// Polyline items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_polyline_items: Vec<PolylineItem>,
    /// Glyph items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_glyph_items: Vec<GlyphItem>,
    /// Tensor glyph items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_tensor_glyph_items: Vec<TensorGlyphItem>,
    /// Sprite items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_sprite_items: Vec<SpriteItem>,
    /// Streamtube items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_streamtube_items: Vec<StreamtubeItem>,
    /// Tube items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_tube_items: Vec<TubeItem>,
    /// Ribbon items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_ribbon_items: Vec<RibbonItem>,
    /// Image slice items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_image_slice_items: Vec<ImageSliceItem>,
    /// Volume surface slice items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_volume_surface_slice_items: Vec<VolumeSurfaceSliceItem>,
    /// Screen image items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_screen_image_items: Vec<ScreenImageItem>,
    /// GPU implicit surface items from the last `prepare()` call, retained for `pick()` dispatch.
    pick_implicit_items: Vec<GpuImplicitPickItem>,
    /// GPU marching cubes jobs from the last `prepare()` call, retained for `pick()` dispatch.
    pick_mc_items: Vec<GpuMcPickItem>,
    /// When `false`, `prepare()` skips populating the CPU pick caches above, so
    /// scenes that never call `pick()`/`pick_rect()` avoid a per-frame deep copy
    /// of all inline geometry. Enable with `set_cpu_pick_cache(true)`.
    cpu_pick_cache_enabled: bool,

    // --- GPU timestamp queries ---
    /// Timestamp query set with `2 * GPU_TS_SLOTS` entries: a begin/end pair per
    /// measured pass (see the `GPU_TS_*` slot constants). `None` when
    /// `TIMESTAMP_QUERY` is unavailable or not yet initialized.
    ts_query_set: Option<wgpu::QuerySet>,
    /// Resolve buffer: `2 * GPU_TS_SLOTS` x u64, GPU-only (`QUERY_RESOLVE | COPY_SRC`).
    ts_resolve_buf: Option<wgpu::Buffer>,
    /// Staging buffer: `2 * GPU_TS_SLOTS` x u64, CPU-readable (`COPY_DST | MAP_READ`).
    ts_staging_buf: Option<wgpu::Buffer>,
    /// Bitmask of `GPU_TS_*` slots whose timestamps were written this frame.
    /// Passes are conditional, so unwritten slots hold stale/undefined query
    /// data; only slots set here are read back. Reset at the start of each frame.
    ///
    /// Atomic so a pass method can set its bit through `&self` without colliding
    /// with the immutable viewport-slot borrows live during pass encoding (and
    /// to keep `ViewportRenderer: Sync`).
    ts_written_mask: std::sync::atomic::AtomicU32,
    /// Snapshot of `ts_written_mask` taken when the queries are resolved, carried
    /// alongside the one-frame-delayed readback so the reader knows which slots
    /// are valid.
    ts_pending_mask: u32,
    /// Nanoseconds per GPU timestamp tick, from `queue.get_timestamp_period()`.
    ts_period: f32,
    /// True when the staging buffer holds resolved timestamps that have not yet
    /// been mapped for readback.
    ts_data_ready: bool,
    /// True when a map of the timestamp staging buffer is in flight. The render
    /// path skips the resolve/copy while this is set so the single staging
    /// buffer is not overwritten before `prepare()` has read it.
    ts_map_inflight: bool,
    /// In-flight timestamp map status, set from the map callback: 0 = pending,
    /// 1 = mapped, 2 = failed. An `Arc<AtomicU8>` rather than an mpsc channel so
    /// `ViewportRenderer` stays `Sync` (mpsc receivers are not).
    ts_map_status: std::sync::Arc<std::sync::atomic::AtomicU8>,

    /// Per-phase CPU timings accumulated during the current `prepare()` call,
    /// copied into `FrameStats::prepare_breakdown` at the end of the frame.
    prepare_breakdown: crate::renderer::stats::PrepareBreakdown,

    // --- Per-pass degradation state ---
    /// Tiered degradation ladder position (0 = none, 1 = shadows, 2 = volumes, 3 = effects).
    /// Advanced one step per over-budget frame once render scale hits minimum;
    /// reversed one step per comfortably-under-budget frame.
    degradation_tier: u8,
    /// Whether the shadow pass was skipped this frame due to budget pressure.
    /// Computed once per frame at the top of prepare() and used by both
    /// prepare_scene_internal and reported in FrameStats.
    degradation_shadows_skipped: bool,
    /// Whether volume raymarch step size was doubled this frame due to budget pressure.
    degradation_volume_quality_reduced: bool,
    /// Whether SSAO, contact shadows, and bloom were skipped this frame.
    /// Set in prepare(); read by the render path.
    degradation_effects_throttled: bool,

    /// Lights dropped by the CPU frustum cull on the most recent frame.
    /// Surfaced through the cluster debug overlay when enabled.
    pub(crate) last_frustum_culled_lights: u32,
    /// Most recent cluster build readback. Populated when a frame's
    /// `ViewportFrame::cluster_stats_request` was true.
    pub(crate) last_cluster_stats: Option<crate::resources::clustered::ClusterStats>,
}

impl ViewportRenderer {
    /// Create a new renderer with default settings (no MSAA).
    /// Call once at application startup.
    pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
        Self::with_sample_count(device, target_format, 1)
    }

    /// Create a new renderer with the specified MSAA sample count (1, 2, or 4).
    ///
    /// When using MSAA (sample_count > 1), the caller must create multisampled
    /// colour and depth textures and use them as render pass attachments with the
    /// final surface texture as the resolve target.
    pub fn with_sample_count(
        device: &wgpu::Device,
        target_format: wgpu::TextureFormat,
        sample_count: u32,
    ) -> Self {
        Self::with_sample_count_and_cache(device, target_format, sample_count, None)
    }

    /// Create a renderer, seeding the GPU pipeline cache from previously saved
    /// data so shader compilation can be skipped on later launches.
    ///
    /// Pass the bytes returned by an earlier [`pipeline_cache_data`](Self::pipeline_cache_data)
    /// call, or `None` on first run. The cache only takes effect when the device
    /// was created with `Features::PIPELINE_CACHE`; otherwise the data is ignored
    /// and this matches [`new`](Self::new).
    pub fn new_with_pipeline_cache(
        device: &wgpu::Device,
        target_format: wgpu::TextureFormat,
        pipeline_cache_data: Option<&[u8]>,
    ) -> Self {
        Self::with_sample_count_and_cache(device, target_format, 1, pipeline_cache_data)
    }

    /// Returns the current contents of the GPU pipeline cache, suitable for
    /// persisting and feeding back into [`new_with_pipeline_cache`](Self::new_with_pipeline_cache)
    /// on the next launch. `None` when the device lacks `Features::PIPELINE_CACHE`.
    pub fn pipeline_cache_data(&self) -> Option<Vec<u8>> {
        self.resources.pipeline_cache.as_ref()?.get_data()
    }

    /// Like [`with_sample_count`](Self::with_sample_count) with an MSAA count and
    /// an optional saved pipeline cache.
    pub fn with_sample_count_and_cache(
        device: &wgpu::Device,
        target_format: wgpu::TextureFormat,
        sample_count: u32,
        pipeline_cache_data: Option<&[u8]>,
    ) -> Self {
        let gpu_culling_supported = device
            .features()
            .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE);
        Self {
            resources: ViewportGpuResources::new_with_cache(
                device,
                target_format,
                sample_count,
                pipeline_cache_data,
            ),
            instancing: InstancingState::new(gpu_culling_supported),
            item_type_plugins: std::collections::HashMap::new(),
            plugin_frame_index: 0,
            last_stats: crate::renderer::stats::FrameStats::default(),
            prepare_breakdown: crate::renderer::stats::PrepareBreakdown::default(),
            point_cloud_gpu_data: Vec::new(),
            glyph_gpu_data: Vec::new(),
            tensor_glyph_gpu_data: Vec::new(),
            polyline_gpu_data: Vec::new(),
            volume_gpu_data: Vec::new(),
            streamtube_gpu_data: Vec::new(),
            tube_gpu_data: Vec::new(),
            ribbon_gpu_data: Vec::new(),
            streamtube_selected_gpu_indices: Vec::new(),
            tube_selected_gpu_indices: Vec::new(),
            ribbon_selected_gpu_indices: Vec::new(),
            polyline_selected_gpu_indices: Vec::new(),
            image_slice_gpu_data: Vec::new(),
            volume_surface_slice_gpu_data: Vec::new(),
            sprite_gpu_data: Vec::new(),
            mesh_instance_gpu_data: Vec::new(),
            particle_gpu_data: Vec::new(),
            sprite_refraction_resolves: Vec::new(),
            gaussian_splat_draw_data: Vec::new(),
            lic_gpu_data: Vec::new(),
            implicit_gpu_data: Vec::new(),
            decal_gpu_data: Vec::new(),
            decal_exclude_items: Vec::new(),
            mc_gpu_data: Vec::new(),
            screen_image_gpu_data: Vec::new(),
            overlay_image_gpu_data: Vec::new(),
            label_gpu_data: None,
            scalar_bar_gpu_data: None,
            ruler_gpu_data: None,
            loading_bar_gpu_data: None,
            overlay_rect_gpu_data: None,
            overlay_shape_gpu_data: None,
            backdrop_blur_state: None,
            viewport_slots: Vec::new(),
            compute_filter_results: Vec::new(),
            mesh_uniforms: PerObjectState::new(),
            shadow: ShadowState::new(),
            runtime_mode: crate::renderer::stats::RuntimeMode::Interactive,
            performance_policy: crate::renderer::stats::PerformancePolicy::default(),
            upload_budget: None,
            current_render_scale: 1.0,
            start_instant: std::time::Instant::now(),
            last_prepare_instant: None,
            frame_counter: 0,
            lod_levels: std::collections::HashMap::new(),
            mesh_instance_lod_levels: std::collections::HashMap::new(),
            pick_scene_items: Vec::new(),
            pick_point_cloud_items: Vec::new(),
            pick_splat_items: Vec::new(),
            pick_volume_items: Vec::new(),
            pick_scatter_volume_items: Vec::new(),
            prepared_scatter_volumes: Vec::new(),
            prepared_refraction_volumes: Vec::new(),
            scatter_viewport_states: Vec::new(),
            pick_volume_mesh_items: Vec::new(),
            pick_polyline_items: Vec::new(),
            pick_glyph_items: Vec::new(),
            pick_tensor_glyph_items: Vec::new(),
            pick_sprite_items: Vec::new(),
            pick_streamtube_items: Vec::new(),
            pick_tube_items: Vec::new(),
            pick_ribbon_items: Vec::new(),
            pick_image_slice_items: Vec::new(),
            pick_volume_surface_slice_items: Vec::new(),
            pick_screen_image_items: Vec::new(),
            pick_implicit_items: Vec::new(),
            pick_mc_items: Vec::new(),
            cpu_pick_cache_enabled: false,
            ts_query_set: None,
            ts_resolve_buf: None,
            ts_staging_buf: None,
            ts_period: 1.0,
            ts_data_ready: false,
            ts_map_inflight: false,
            ts_map_status: std::sync::Arc::new(std::sync::atomic::AtomicU8::new(0)),
            ts_written_mask: std::sync::atomic::AtomicU32::new(0),
            ts_pending_mask: 0,
            degradation_tier: 0,
            degradation_shadows_skipped: false,
            degradation_volume_quality_reduced: false,
            degradation_effects_throttled: false,
            last_frustum_culled_lights: 0,
            last_cluster_stats: None,
        }
    }

    /// Access the underlying GPU resources (e.g. for mesh uploads).
    pub fn resources(&self) -> &ViewportGpuResources {
        &self.resources
    }

    /// Performance counters from the last completed frame.
    pub fn last_frame_stats(&self) -> crate::renderer::stats::FrameStats {
        self.last_stats
    }

    /// Diagnostics from the cluster build pass on the most recent frame that
    /// requested them (`ViewportFrame::cluster_stats_request`). Returns
    /// `None` until a request has been served.
    pub fn cluster_stats(&self) -> Option<crate::resources::clustered::ClusterStats> {
        self.last_cluster_stats
    }

    /// Disable GPU-driven culling, reverting to the direct draw path.
    ///
    /// Has no effect when the device does not support `INDIRECT_FIRST_INSTANCE`
    /// (culling is already disabled on those devices).
    pub fn disable_gpu_driven_culling(&mut self) {
        self.instancing.gpu_culling_enabled = false;
    }

    /// Force a full instance buffer upload on the next frame.
    ///
    /// Normally the renderer skips GPU writes for instanced batches whose data
    /// has not changed since the last upload. Call this when you have mutated
    /// batch-relevant state through a path the renderer cannot observe (for
    /// example, directly modifying GPU buffer contents or scene items after
    /// `collect_render_items` runs). The flag is consumed once and resets
    /// automatically after the next `prepare` call.
    pub fn force_dirty(&mut self) {
        self.instancing.force_full_upload = true;
        // Also invalidate the generation cache so the next prepare is guaranteed
        // to enter the rebuild path even if the scene generation is unchanged.
        self.instancing.last_scene_generation = u64::MAX;
    }

    /// Re-enable GPU-driven culling after a call to `disable_gpu_driven_culling`.
    ///
    /// Has no effect when the device does not support `INDIRECT_FIRST_INSTANCE`.
    pub fn enable_gpu_driven_culling(&mut self) {
        if self.instancing.gpu_culling_supported {
            self.instancing.gpu_culling_enabled = true;
        }
    }

    /// Cap the per-frame cost of running upload-job apply closures.
    ///
    /// `None` is the default and matches the historical behaviour:
    /// `prepare` drains every completed upload's apply step in one
    /// shot. `Some(d)` switches `prepare` over to
    /// `process_uploads_with_budget` so applies that overflow the
    /// budget spill to the next frame. Useful when a stress load lands
    /// many heavy completions on the same frame and the bunched apply
    /// work shows up as one fat frame at the end of the load.
    pub fn set_upload_budget(&mut self, budget: Option<std::time::Duration>) {
        self.upload_budget = budget;
    }

    /// Currently configured upload budget. See `set_upload_budget`.
    pub fn upload_budget(&self) -> Option<std::time::Duration> {
        self.upload_budget
    }

    /// Set the runtime mode controlling internal default behavior.
    ///
    /// - [`RuntimeMode::Interactive`]: full picking rate, full quality (default).
    /// - [`RuntimeMode::Playback`]: picking throttled to reduce CPU overhead during animation.
    /// - [`RuntimeMode::Paused`]: full picking rate, full quality.
    /// - [`RuntimeMode::Capture`]: full quality, intended for screenshot/export workflows.
    pub fn set_runtime_mode(&mut self, mode: crate::renderer::stats::RuntimeMode) {
        self.runtime_mode = mode;
    }

    /// Return the current runtime mode.
    pub fn runtime_mode(&self) -> crate::renderer::stats::RuntimeMode {
        self.runtime_mode
    }

    /// Enable or disable the CPU pick cache.
    ///
    /// When enabled, `prepare()` retains a copy of the frame's pickable items so
    /// `pick()` and `pick_rect()` can run later (e.g. on a mouse click) without the
    /// scene data. This copies all inline point/glyph/curve geometry each frame, so it
    /// is disabled by default: turn it on only when using the CPU `pick()`/`pick_rect()`
    /// path. The GPU path (`pick_scene_gpu`) and the renderer-free
    /// `interaction::picking` functions do not need it.
    pub fn set_cpu_pick_cache(&mut self, enabled: bool) {
        if !enabled && self.cpu_pick_cache_enabled {
            self.clear_pick_cache();
        }
        self.cpu_pick_cache_enabled = enabled;
    }

    /// Whether the CPU pick cache is enabled. See `set_cpu_pick_cache`.
    pub fn cpu_pick_cache(&self) -> bool {
        self.cpu_pick_cache_enabled
    }

    /// Set the performance policy controlling target FPS, render scale bounds,
    /// and permitted quality reductions.
    ///
    /// The internal adaptation controller activates when
    /// `policy.allow_dynamic_resolution` is `true` and `policy.target_fps` is
    /// `Some`. It adjusts `render_scale` within `[min_render_scale,
    /// max_render_scale]` each frame based on `total_frame_ms`.
    pub fn set_performance_policy(&mut self, policy: crate::renderer::stats::PerformancePolicy) {
        self.performance_policy = policy;
        // Clamp current scale into the new bounds immediately.
        self.current_render_scale = self
            .current_render_scale
            .clamp(policy.min_render_scale, policy.max_render_scale);
    }

    /// Return the active performance policy.
    pub fn performance_policy(&self) -> crate::renderer::stats::PerformancePolicy {
        self.performance_policy
    }

    /// Manually set the render scale.
    ///
    /// Effective when `performance_policy.allow_dynamic_resolution` is `false`.
    /// When dynamic resolution is enabled the adaptation controller overrides
    /// this value each frame.
    ///
    /// The value is clamped to `[policy.min_render_scale, policy.max_render_scale]`.
    ///
    /// Works on both the LDR and HDR render paths. On the HDR path, the scene,
    /// bloom, SSAO, tone-map, and FXAA all run at the scaled resolution; the
    /// result is upscale-blitted to native resolution before overlays and grid.
    pub fn set_render_scale(&mut self, scale: f32) {
        self.current_render_scale = scale.clamp(
            self.performance_policy.min_render_scale,
            self.performance_policy.max_render_scale,
        );
    }

    /// Set the target frame rate used to compute [`FrameStats::missed_budget`].
    ///
    /// Convenience wrapper that updates `performance_policy.target_fps`.
    pub fn set_target_fps(&mut self, fps: Option<f32>) {
        self.performance_policy.target_fps = fps;
    }

    /// Mutable access to the underlying GPU resources (e.g. for mesh uploads).
    pub fn resources_mut(&mut self) -> &mut ViewportGpuResources {
        &mut self.resources
    }

    /// Returns true when the current frame is rendered via the instanced draw path.
    ///
    /// When true, edits to mesh.wgsl shadow sampling code have no effect - the active
    /// shader is mesh_instanced.wgsl. Check this before testing shader changes.
    pub fn is_using_instanced_path(&self) -> bool {
        self.instancing.use_instancing
    }

    /// Returns the number of instanced batches prepared for the current frame.
    ///
    /// Zero when using the non-instanced path. Each batch corresponds to a distinct
    /// (MeshId, material) combination in the scene.
    pub fn instanced_batch_count(&self) -> usize {
        self.instancing.batches.len()
    }

    /// Run the GPU-driven cull compute against a plugin's
    /// [`CullSubmission`](crate::plugin_api::CullSubmission).
    ///
    /// Encodes two compute passes into `encoder`:
    /// 1. one thread per instance, tests AABB against `frustum`, claims a
    ///    visibility slot via atomic add;
    /// 2. one thread per batch, writes a `DrawIndexedIndirect` entry into
    ///    `sub.indirect_out` with the final visible count and zeroes the
    ///    counter for the next call.
    ///
    /// After the encoder runs, draw each batch with
    /// `pass.draw_indexed_indirect(sub.indirect_out, batch_idx * 20)` using
    /// `sub.visible_out` as the per-instance lookup buffer.
    ///
    /// The cull pipeline is created lazily on the first call. Returns
    /// without dispatching if the device does not support
    /// `INDIRECT_FIRST_INSTANCE` (call
    /// [`is_gpu_culling_supported`](Self::is_gpu_culling_supported) first).
    pub fn submit_cull(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        frustum: &crate::camera::frustum::Frustum,
        sub: &crate::plugin_api::CullSubmission<'_>,
    ) {
        if !self.instancing.gpu_culling_supported {
            return;
        }
        if self.instancing.cull_resources.is_none() {
            self.instancing.cull_resources =
                Some(crate::renderer::indirect::CullResources::new(device));
        }
        let cull = self.instancing.cull_resources.as_ref().unwrap();
        cull.dispatch(encoder, device, queue, frustum, None, sub, None);
    }

    /// Same as [`submit_cull`](Self::submit_cull) for one shadow cascade.
    ///
    /// Uploads the frustum to the cascade slot (so a single frame can submit
    /// the main pass plus every cascade without overwriting an in-flight
    /// upload) and forces the cull shader's shadow flag so
    /// `InstanceAabb::cast_shadows = 0` entries are skipped.
    ///
    /// `cascade_idx` must be in `0..4`; values outside that range panic in
    /// debug builds and clamp to 3 in release.
    pub fn submit_cull_shadow(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        cascade_idx: usize,
        cascade_frustum: &crate::camera::frustum::Frustum,
        sub: &crate::plugin_api::CullSubmission<'_>,
    ) {
        if !self.instancing.gpu_culling_supported {
            return;
        }
        debug_assert!(cascade_idx < 4, "cascade_idx must be in 0..4");
        let cascade_idx = cascade_idx.min(3);
        if self.instancing.cull_resources.is_none() {
            self.instancing.cull_resources =
                Some(crate::renderer::indirect::CullResources::new(device));
        }
        let cull = self.instancing.cull_resources.as_ref().unwrap();
        cull.dispatch(
            encoder,
            device,
            queue,
            cascade_frustum,
            Some(cascade_idx),
            sub,
            None,
        );
    }

    /// Convenience wrapper around [`submit_cull`](Self::submit_cull) for the
    /// common case of one mesh with N instances.
    ///
    /// The renderer fills its scratch [`BatchMeta`] slot from `draw`, zeroes
    /// its scratch counter, seeds the indirect entry, and runs a one-batch
    /// cull. Plugins that only have a single mesh per submission don't have
    /// to allocate either buffer themselves.
    ///
    /// `indirect_out` must hold one `DrawIndexedIndirect` entry (20 bytes).
    pub fn submit_cull_single_mesh(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        frustum: &crate::camera::frustum::Frustum,
        instance_aabbs: &wgpu::Buffer,
        instance_count: u32,
        visible_out: &wgpu::Buffer,
        indirect_out: &wgpu::Buffer,
        draw: crate::plugin_api::SingleMeshDraw,
        shadow_pass: bool,
    ) {
        self.dispatch_cull_single_mesh(
            device,
            queue,
            encoder,
            frustum,
            None,
            instance_aabbs,
            instance_count,
            visible_out,
            indirect_out,
            draw,
            shadow_pass,
        );
    }

    /// Single-mesh shadow variant of
    /// [`submit_cull_single_mesh`](Self::submit_cull_single_mesh).
    pub fn submit_cull_shadow_single_mesh(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        cascade_idx: usize,
        cascade_frustum: &crate::camera::frustum::Frustum,
        instance_aabbs: &wgpu::Buffer,
        instance_count: u32,
        visible_out: &wgpu::Buffer,
        indirect_out: &wgpu::Buffer,
        draw: crate::plugin_api::SingleMeshDraw,
    ) {
        debug_assert!(cascade_idx < 4, "cascade_idx must be in 0..4");
        let cascade_idx = cascade_idx.min(3);
        self.dispatch_cull_single_mesh(
            device,
            queue,
            encoder,
            cascade_frustum,
            Some(cascade_idx),
            instance_aabbs,
            instance_count,
            visible_out,
            indirect_out,
            draw,
            true,
        );
    }

    #[allow(clippy::too_many_arguments)]
    fn dispatch_cull_single_mesh(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        frustum: &crate::camera::frustum::Frustum,
        cascade: Option<usize>,
        instance_aabbs: &wgpu::Buffer,
        instance_count: u32,
        visible_out: &wgpu::Buffer,
        indirect_out: &wgpu::Buffer,
        draw: crate::plugin_api::SingleMeshDraw,
        shadow_pass: bool,
    ) {
        if !self.instancing.gpu_culling_supported {
            return;
        }
        if self.instancing.cull_resources.is_none() {
            self.instancing.cull_resources =
                Some(crate::renderer::indirect::CullResources::new(device));
        }
        let cull = self.instancing.cull_resources.as_ref().unwrap();
        let (meta_buf, counter_buf) = cull.scratch_single_mesh_buffers();
        let meta = crate::plugin_api::BatchMeta {
            index_count: draw.index_count,
            first_index: draw.first_index,
            instance_offset: 0,
            instance_count,
            vis_offset: 0,
            is_transparent: 0,
            _pad: [0, 0],
        };
        queue.write_buffer(meta_buf, 0, bytemuck::bytes_of(&meta));
        queue.write_buffer(counter_buf, 0, &[0u8; 4]);
        // Seed the static fields of the indirect entry; the compute pass
        // overwrites `instance_count` with the final visible count.
        let seed: [u32; 5] = [
            draw.index_count,
            0,
            draw.first_index,
            draw.base_vertex as u32,
            draw.first_instance,
        ];
        queue.write_buffer(indirect_out, 0, bytemuck::cast_slice(&seed));

        let sub = crate::plugin_api::CullSubmission {
            instance_aabbs,
            instance_count,
            batch_meta: meta_buf,
            batch_count: 1,
            counter: counter_buf,
            visible_out,
            indirect_out,
            shadow_pass,
        };
        cull.dispatch(encoder, device, queue, frustum, cascade, &sub, None);
    }

    /// Register an [`ItemTypePlugin`](crate::plugin_api::ItemTypePlugin).
    ///
    /// Invokes the plugin's `init_gpu` against the current device and
    /// shared bind layout, then stores it keyed by `type_name()` for the
    /// remainder of the renderer's lifetime. Registering a second plugin
    /// with the same `type_name` replaces the first.
    ///
    /// The renderer will dispatch `prepare` and `paint` to the plugin on
    /// every frame where
    /// [`SceneFrame::submit_plugin_items`](crate::renderer::SceneFrame::submit_plugin_items)
    /// has populated a collection under the same name.
    pub fn with_item_type_plugin(
        &mut self,
        device: &wgpu::Device,
        mut plugin: Box<dyn crate::plugin_api::ItemTypePlugin>,
    ) {
        let shared = self.resources.shared_bindings();
        plugin.init_gpu(device, &shared);
        let name = plugin.type_name();
        self.item_type_plugins.insert(name, plugin);
    }

    /// Returns true when an item-type plugin with `type_name` is
    /// registered.
    pub fn has_item_type_plugin(&self, type_name: &str) -> bool {
        self.item_type_plugins.contains_key(type_name)
    }

    /// Walk registered item-type plugins, invoke `prepare` for each one
    /// that has a matching collection submitted on `frame.scene`, and
    /// return the concatenated command buffers.
    ///
    /// Called internally from the lib's prepare paths; not part of the
    /// consumer-facing API.
    pub(crate) fn dispatch_plugin_prepare(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        frame: &FrameData,
    ) -> Vec<wgpu::CommandBuffer> {
        if self.item_type_plugins.is_empty() || frame.scene.plugin_items.is_empty() {
            return Vec::new();
        }
        self.plugin_frame_index = self.plugin_frame_index.wrapping_add(1);
        let mut bufs: Vec<wgpu::CommandBuffer> = Vec::new();
        for (name, plugin) in self.item_type_plugins.iter_mut() {
            if let Some(items) = frame.scene.plugin_items.get(*name) {
                // Constructed per plugin because `Jobs` borrows `&resources`
                // and the borrow only needs to live for this iteration.
                let ctx = crate::plugin_api::ItemFrameContext {
                    camera: &frame.camera.render_camera,
                    viewport_size: glam::Vec2::from(frame.camera.viewport_size),
                    viewport_index: frame.camera.viewport_index,
                    frame_index: self.plugin_frame_index,
                    jobs: crate::resources::Jobs::new(&self.resources),
                };
                bufs.extend(plugin.prepare(device, queue, &ctx, items.as_ref()));
            }
        }
        bufs
    }

    /// Walk registered item-type plugins and invoke `paint` for each one
    /// that has a matching collection submitted on `frame.scene`.
    ///
    /// Called from inside the lib's HDR scene pass between built-in
    /// opaques and the skybox.
    pub(crate) fn dispatch_plugin_paint<'rp>(
        &'rp self,
        pass: &mut wgpu::RenderPass<'rp>,
        frame: &'rp FrameData,
    ) {
        if self.item_type_plugins.is_empty() || frame.scene.plugin_items.is_empty() {
            return;
        }
        let ctx = crate::plugin_api::PaintContext {
            camera: &frame.camera.render_camera,
            viewport_size: glam::Vec2::from(frame.camera.viewport_size),
            viewport_index: frame.camera.viewport_index,
            frame_index: self.plugin_frame_index,
        };
        for (name, plugin) in self.item_type_plugins.iter() {
            if let Some(items) = frame.scene.plugin_items.get(*name) {
                plugin.paint(pass, &ctx, items.as_ref());
            }
        }
    }

    /// Walk registered plugins and invoke `paint_transparent` for each
    /// one whose collection is on `frame.scene`.
    ///
    /// Called from inside the lib's OIT render pass, after built-in
    /// transparent draws.
    pub(crate) fn dispatch_plugin_paint_transparent<'rp>(
        &'rp self,
        pass: &mut wgpu::RenderPass<'rp>,
        frame: &'rp FrameData,
    ) {
        if self.item_type_plugins.is_empty() || frame.scene.plugin_items.is_empty() {
            return;
        }
        let ctx = crate::plugin_api::PaintContext {
            camera: &frame.camera.render_camera,
            viewport_size: glam::Vec2::from(frame.camera.viewport_size),
            viewport_index: frame.camera.viewport_index,
            frame_index: self.plugin_frame_index,
        };
        for (name, plugin) in self.item_type_plugins.iter() {
            if let Some(items) = frame.scene.plugin_items.get(*name) {
                plugin.paint_transparent(pass, &ctx, items.as_ref());
            }
        }
    }

    /// Walk registered plugins and invoke `cast_shadow_pass` for the
    /// given cascade.
    ///
    /// Currently unused: the shadow-pass call site inlines the plugin
    /// dispatch because the surrounding scope holds a mutable borrow of
    /// `self.resources` that blocks a normal `&self` method call. Kept
    /// alongside the other dispatchers as the natural shape; a future
    /// refactor that splits the resources borrow can switch back.
    #[allow(dead_code)]
    pub(crate) fn dispatch_plugin_shadow<'rp>(
        &'rp self,
        pass: &mut wgpu::RenderPass<'rp>,
        frame: &'rp FrameData,
        cascade_idx: u32,
        light_view_proj: glam::Mat4,
    ) {
        if self.item_type_plugins.is_empty() || frame.scene.plugin_items.is_empty() {
            return;
        }
        let ctx = crate::plugin_api::ShadowCastContext {
            cascade_idx,
            light_view_proj,
            camera: &frame.camera.render_camera,
            viewport_index: frame.camera.viewport_index,
            frame_index: self.plugin_frame_index,
        };
        for (name, plugin) in self.item_type_plugins.iter() {
            if let Some(items) = frame.scene.plugin_items.get(*name) {
                plugin.cast_shadow_pass(pass, &ctx, items.as_ref());
            }
        }
    }

    /// Walk registered plugins and invoke `cull` for each one whose
    /// collection is on `frame.scene`.
    ///
    /// Called from the lib's prepare path once the camera frustum for
    /// the frame is known.
    pub(crate) fn dispatch_plugin_cull(
        &mut self,
        frustum: &crate::camera::frustum::Frustum,
        frame: &FrameData,
    ) {
        if self.item_type_plugins.is_empty() || frame.scene.plugin_items.is_empty() {
            return;
        }
        for (name, plugin) in self.item_type_plugins.iter_mut() {
            if let Some(items) = frame.scene.plugin_items.get(*name) {
                let ctx = crate::plugin_api::ItemFrameContext {
                    camera: &frame.camera.render_camera,
                    viewport_size: glam::Vec2::from(frame.camera.viewport_size),
                    viewport_index: frame.camera.viewport_index,
                    frame_index: self.plugin_frame_index,
                    jobs: crate::resources::Jobs::new(&self.resources),
                };
                plugin.cull(frustum, &ctx, items.as_ref());
            }
        }
    }

    /// Walk registered item-type plugins and invoke `outline_mask` for
    /// each one whose collection is on `frame.scene`.
    ///
    /// Called from inside the lib's outline-mask render pass.
    pub(crate) fn dispatch_plugin_outline_mask<'rp>(
        &'rp self,
        pass: &mut wgpu::RenderPass<'rp>,
        frame: &'rp FrameData,
    ) {
        if self.item_type_plugins.is_empty() || frame.scene.plugin_items.is_empty() {
            return;
        }
        let ctx = crate::plugin_api::OutlineMaskContext {
            camera: &frame.camera.render_camera,
            viewport_size: glam::Vec2::from(frame.camera.viewport_size),
            viewport_index: frame.camera.viewport_index,
            frame_index: self.plugin_frame_index,
        };
        for (name, plugin) in self.item_type_plugins.iter() {
            if let Some(items) = frame.scene.plugin_items.get(*name) {
                plugin.outline_mask(pass, &ctx, items.as_ref());
            }
        }
    }

    /// True when the device supports the features GPU-driven culling needs.
    ///
    /// Plugins should gate `submit_cull` calls on this. If false, the lib
    /// silently no-ops the submission and the plugin must fall back to
    /// direct draws.
    pub fn is_gpu_culling_supported(&self) -> bool {
        self.instancing.gpu_culling_supported
    }

    /// Returns per-frame shadow and lighting pipeline statistics for debug inspection.
    ///
    /// All fields reflect the most recently completed `prepare` call (one frame
    /// behind the display). Returns default values before the first `prepare` call.
    pub fn shadow_debug_stats(&self) -> ShadowDebugStats {
        ShadowDebugStats {
            using_instanced_path: self.instancing.use_instancing,
            instanced_batch_count: self.instancing.batches.len(),
            cascade_count: self.shadow.last_cascade_count,
            cascade_splits: self.shadow.last_cascade_splits,
            shadow_atlas_resolution: self.shadow.last_shadow_atlas_resolution,
            shadow_extent_world: self.shadow.last_shadow_extent,
            contact_shadow_active: self.shadow.last_contact_shadow_active,
        }
    }

    /// Read the debug values at a specific pixel from the per-fragment storage buffer.
    ///
    /// Returns `None` when debug_vis is inactive (no buffer allocated) or when `(x, y)`
    /// is outside the viewport. The four channels correspond to the current R/G/B channel
    /// selectors plus 1.0 for alpha.
    ///
    /// This submits a GPU-to-CPU copy and waits synchronously. Only call from outside
    /// a render pass (e.g., in the next frame's prepare step), not inside paint callbacks.
    ///
    /// The returned values are from the previous rendered frame.
    pub fn read_debug_pixel(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        x: u32,
        y: u32,
    ) -> Option<[f32; 4]> {
        // Use the primary viewport slot (index 0).
        let slot = self.viewport_slots.first()?;
        let buf = slot.debug_frag_buf.as_ref()?;
        let (vw, vh) = slot.debug_frag_dims;
        if x >= vw || y >= vh {
            return None;
        }
        let byte_offset = ((y as u64) * (vw as u64) + (x as u64)) * 16;
        let staging = device.create_buffer(&wgpu::BufferDescriptor {
            label: None,
            size: 16,
            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let mut encoder =
            device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
        encoder.copy_buffer_to_buffer(buf, byte_offset, &staging, 0, 16);
        queue.submit(Some(encoder.finish()));
        let slice = staging.slice(..);
        let (tx, rx) = std::sync::mpsc::channel::<Result<(), wgpu::BufferAsyncError>>();
        slice.map_async(wgpu::MapMode::Read, move |r| {
            let _ = tx.send(r);
        });
        let _ = device.poll(wgpu::PollType::Wait {
            submission_index: None,
            timeout: Some(std::time::Duration::from_secs(5)),
        });
        rx.recv().ok()?.ok()?;
        let data = slice.get_mapped_range();
        Some(bytemuck::pod_read_unaligned::<[f32; 4]>(&data))
    }

    /// Upload a Gaussian splat set to the GPU.
    ///
    /// Call once per splat set at startup or when it changes. The returned
    /// [`GaussianSplatId`] is valid until [`remove_gaussian_splats`](Self::remove_gaussian_splats) is called.
    ///
    /// # Errors
    ///
    /// Returns [`ViewportError::InvalidGaussianSplatData`](crate::error::ViewportError::InvalidGaussianSplatData)
    /// if `data.positions` is empty or if `positions`, `scales`, `rotations`, and `opacities`
    /// differ in length.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use viewport_lib::error::ViewportError;
    /// # use viewport_lib::renderer::{GaussianSplatData, ViewportRenderer};
    /// # fn demo(renderer: &mut ViewportRenderer, device: &wgpu::Device, queue: &wgpu::Queue) {
    /// let result = renderer.upload_gaussian_splats(device, queue, &GaussianSplatData::default());
    /// assert!(matches!(result, Err(ViewportError::InvalidGaussianSplatData { .. })));
    /// # }
    /// ```
    pub fn upload_gaussian_splats(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        data: &GaussianSplatData,
    ) -> crate::error::ViewportResult<GaussianSplatId> {
        self.resources.upload_gaussian_splats(device, queue, data)
    }

    /// Remove an uploaded Gaussian splat set by handle.
    ///
    /// After this call the `id` is invalid and must not be submitted in `SceneFrame`.
    pub fn remove_gaussian_splats(&mut self, id: GaussianSplatId) {
        self.resources.remove_gaussian_splats(id);
    }

    /// Upload an equirectangular HDR environment map and precompute IBL textures.
    ///
    /// `pixels` is row-major RGBA f32 data (4 floats per texel), `width`x`height`.
    /// This rebuilds camera bind groups so shaders immediately see the new textures.
    ///
    /// # Errors
    ///
    /// Returns [`ViewportError::InvalidTextureData`](crate::error::ViewportError::InvalidTextureData)
    /// if `pixels.len()` does not equal `width * height * 4`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use viewport_lib::error::ViewportError;
    /// # use viewport_lib::renderer::ViewportRenderer;
    /// # fn demo(renderer: &mut ViewportRenderer, device: &wgpu::Device, queue: &wgpu::Queue) {
    /// // 2x2 RGBA image requires exactly 16 floats.
    /// let result = renderer.upload_environment_map(device, queue, &[0.0f32; 12], 2, 2);
    /// assert!(matches!(result, Err(ViewportError::InvalidTextureData { expected: 16, actual: 12 })));
    /// # }
    /// ```
    pub fn upload_environment_map(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        pixels: &[f32],
        width: u32,
        height: u32,
    ) -> crate::error::ViewportResult<()> {
        crate::resources::environment::upload_environment_map(
            &mut self.resources,
            device,
            queue,
            pixels,
            width,
            height,
        )?;
        self.rebuild_camera_bind_groups(device);
        Ok(())
    }

    /// Current state of an in-flight upload job.
    pub fn upload_status(&self, id: crate::resources::JobId) -> crate::resources::UploadStatus {
        self.resources.upload_status(id)
    }

    /// Count of upload jobs still in flight.
    pub fn uploads_pending(&self) -> usize {
        self.resources.uploads_pending()
    }

    /// Wall-clock work duration recorded for an async upload job. See
    /// [`ViewportGpuResources::job_duration`].
    pub fn job_duration(&self, id: crate::resources::JobId) -> Option<std::time::Duration> {
        self.resources.job_duration(id)
    }

    /// Drop the recorded duration for `id` after reading it. See
    /// [`ViewportGpuResources::drop_job_duration`].
    pub fn drop_job_duration(&mut self, id: crate::resources::JobId) {
        self.resources.drop_job_duration(id);
    }

    /// Start an asynchronous 3D volume texture upload. See
    /// [`ViewportGpuResources::begin_upload_volume`].
    pub fn begin_upload_volume(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        data: Vec<f32>,
        dims: [u32; 3],
    ) -> crate::error::ViewportResult<crate::resources::JobId> {
        self.resources
            .begin_upload_volume(device, queue, data, dims)
    }

    /// Take the volume id produced by a completed
    /// [`begin_upload_volume`](Self::begin_upload_volume) job.
    pub fn upload_result_volume(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::resources::VolumeId> {
        self.resources.upload_result_volume(id)
    }

    /// Start an asynchronous marching-cubes-ready volume upload. See
    /// [`ViewportGpuResources::begin_upload_volume_for_mc`].
    pub fn begin_upload_volume_for_mc(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        vol: crate::geometry::marching_cubes::VolumeData,
    ) -> crate::resources::JobId {
        self.resources
            .begin_upload_volume_for_mc(device, queue, vol)
    }

    /// Take the [`VolumeGpuId`](crate::resources::VolumeGpuId) produced by a
    /// completed [`begin_upload_volume_for_mc`](Self::begin_upload_volume_for_mc) job.
    pub fn upload_result_volume_mc(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::resources::VolumeGpuId> {
        self.resources.upload_result_volume_mc(id)
    }

    /// Start an asynchronous boundary-only volume mesh upload. See
    /// [`ViewportGpuResources::begin_upload_volume_mesh`].
    pub fn begin_upload_volume_mesh(
        &mut self,
        device: &wgpu::Device,
        data: crate::resources::volume_mesh::VolumeMeshData,
    ) -> crate::resources::JobId {
        self.resources.begin_upload_volume_mesh(device, data)
    }

    /// Take the [`VolumeMeshItem`](crate::VolumeMeshItem)
    /// produced by a completed
    /// [`begin_upload_volume_mesh`](Self::begin_upload_volume_mesh) job.
    pub fn upload_result_volume_mesh(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::VolumeMeshItem> {
        self.resources.upload_result_volume_mesh(id)
    }

    /// Start an asynchronous clipped volume mesh upload. See
    /// [`ViewportGpuResources::begin_upload_clipped_volume_mesh`].
    pub fn begin_upload_clipped_volume_mesh(
        &mut self,
        device: &wgpu::Device,
        data: crate::resources::volume_mesh::VolumeMeshData,
        clip_planes: Vec<[f32; 4]>,
    ) -> crate::resources::JobId {
        self.resources
            .begin_upload_clipped_volume_mesh(device, data, clip_planes)
    }

    /// Take the [`VolumeMeshItem`](crate::VolumeMeshItem)
    /// produced by a completed
    /// [`begin_upload_clipped_volume_mesh`](Self::begin_upload_clipped_volume_mesh) job.
    pub fn upload_result_clipped_volume_mesh(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::VolumeMeshItem> {
        self.resources.upload_result_clipped_volume_mesh(id)
    }

    /// Start an asynchronous sparse voxel grid upload. See
    /// [`ViewportGpuResources::begin_upload_sparse_volume_grid_data`].
    pub fn begin_upload_sparse_volume_grid_data(
        &mut self,
        device: &wgpu::Device,
        data: crate::resources::SparseVolumeGridData,
    ) -> crate::resources::JobId {
        self.resources
            .begin_upload_sparse_volume_grid_data(device, data)
    }

    /// Take the [`MeshId`](crate::resources::mesh_store::MeshId) produced by a completed
    /// [`begin_upload_sparse_volume_grid_data`](Self::begin_upload_sparse_volume_grid_data)
    /// job.
    pub fn upload_result_sparse_volume_grid(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::resources::mesh_store::MeshId> {
        self.resources.upload_result_sparse_volume_grid(id)
    }

    /// Start an asynchronous Gaussian splat upload. See
    /// [`ViewportGpuResources::begin_upload_gaussian_splats`].
    pub fn begin_upload_gaussian_splats(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        data: crate::renderer::GaussianSplatData,
    ) -> crate::error::ViewportResult<crate::resources::JobId> {
        self.resources
            .begin_upload_gaussian_splats(device, queue, data)
    }

    /// Take the [`GaussianSplatId`](crate::renderer::GaussianSplatId) produced by a
    /// completed [`begin_upload_gaussian_splats`](Self::begin_upload_gaussian_splats) job.
    pub fn upload_result_gaussian_splats(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::renderer::GaussianSplatId> {
        self.resources.upload_result_gaussian_splats(id)
    }

    /// Start an asynchronous overlay texture upload. See
    /// [`ViewportGpuResources::begin_upload_overlay_texture`].
    pub fn begin_upload_overlay_texture(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        rgba_data: Vec<u8>,
    ) -> crate::error::ViewportResult<crate::resources::JobId> {
        self.resources
            .begin_upload_overlay_texture(device, queue, width, height, rgba_data)
    }

    /// Take the [`OverlayTextureId`](crate::renderer::OverlayTextureId) produced by a
    /// completed [`begin_upload_overlay_texture`](Self::begin_upload_overlay_texture) job.
    pub fn upload_result_overlay_texture(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::renderer::OverlayTextureId> {
        self.resources.upload_result_overlay_texture(id)
    }

    /// True when no upload jobs are in flight.
    pub fn all_uploads_complete(&self) -> bool {
        self.resources.all_uploads_complete()
    }

    /// Register a callback to fire when an upload job finishes. See
    /// [`ViewportGpuResources::on_upload_complete`] for the semantics.
    pub fn on_upload_complete<F>(&mut self, id: crate::resources::JobId, cb: F)
    where
        F: FnOnce(&crate::resources::UploadStatus) + Send + 'static,
    {
        self.resources.on_upload_complete(id, cb);
    }

    /// Start an asynchronous albedo texture upload. See
    /// [`ViewportGpuResources::begin_upload_texture`] for the semantics.
    pub fn begin_upload_texture(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        rgba: Vec<u8>,
    ) -> crate::error::ViewportResult<crate::resources::JobId> {
        self.resources
            .begin_upload_texture(device, queue, width, height, rgba)
    }

    /// Start an asynchronous normal-map upload. See
    /// [`ViewportGpuResources::begin_upload_normal_map`] for the semantics.
    pub fn begin_upload_normal_map(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        width: u32,
        height: u32,
        rgba: Vec<u8>,
    ) -> crate::error::ViewportResult<crate::resources::JobId> {
        self.resources
            .begin_upload_normal_map(device, queue, width, height, rgba)
    }

    /// Take the texture id from a completed async texture upload. See
    /// [`ViewportGpuResources::upload_result_texture`] for the error
    /// semantics.
    pub fn upload_result_texture(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<u64> {
        self.resources.upload_result_texture(id)
    }

    /// Start an asynchronous mesh upload.
    ///
    /// Returns a `JobId` immediately. The CPU prep (tangent computation,
    /// vertex repack, normal-line build) runs on a worker thread; GPU
    /// buffer creation and store insertion run on the main thread during
    /// the next `process_uploads` call after the worker finishes. Once the
    /// status is `Ready`, take the produced `MeshId` with
    /// `upload_result_mesh`.
    ///
    /// Ownership of `data` transfers into the worker; clone at the call
    /// site if you need to retain it.
    ///
    /// # Errors
    ///
    /// Same validation errors as `upload_mesh_data` (empty mesh, length
    /// mismatch, invalid vertex index), all reported before the job is
    /// submitted.
    pub fn begin_upload_mesh_data(
        &mut self,
        device: &wgpu::Device,
        data: crate::resources::MeshData,
    ) -> crate::error::ViewportResult<crate::resources::JobId> {
        self.resources.begin_upload_mesh_data(device, data)
    }

    /// Take the `MeshId` produced by a completed `begin_upload_mesh_data`
    /// job. See [`ViewportGpuResources::upload_result_mesh`] for the error
    /// semantics.
    pub fn upload_result_mesh(
        &mut self,
        id: crate::resources::JobId,
    ) -> crate::error::ViewportResult<crate::resources::mesh_store::MeshId> {
        self.resources.upload_result_mesh(id)
    }

    /// Start an asynchronous environment-map upload.
    ///
    /// Returns immediately with a `JobId`. The caller drives the upload-job
    /// runner from the renderer's prepare path each frame; once the job
    /// reports `Ready`, the IBL textures are live on the renderer and a
    /// subsequent call to `rebuild_camera_bind_groups` makes them visible
    /// to shaders.
    ///
    /// Ownership of `pixels` transfers into the background worker.
    ///
    /// # Errors
    ///
    /// Returns [`ViewportError::InvalidTextureData`](crate::error::ViewportError::InvalidTextureData)
    /// if `pixels.len() != width * height * 4`.
    pub fn begin_upload_environment_map(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        pixels: Vec<f32>,
        width: u32,
        height: u32,
    ) -> crate::error::ViewportResult<crate::resources::JobId> {
        crate::resources::environment::begin_upload_environment_map(
            &mut self.resources,
            device,
            queue,
            pixels,
            width,
            height,
        )
    }

    /// Rebuild the primary and per-viewport camera bind groups.
    ///
    /// Call after IBL textures are uploaded so the shaders see the new
    /// environment. The synchronous `upload_environment_map` does this
    /// internally; consumers driving the async path through
    /// `begin_upload_environment_map` should call this themselves once the
    /// matching job reports `Ready`.
    pub fn rebuild_camera_bind_groups(&mut self, device: &wgpu::Device) {
        self.resources.camera_bind_group = self.resources.create_camera_bind_group(
            device,
            &self.resources.camera_uniform_buf,
            &self.resources.clip_planes_uniform_buf,
            &self.resources.shadow_info_buf,
            &self.resources.clip_volume_uniform_buf,
            &self.resources.debug_frag_sentinel_buf,
            "camera_bind_group",
        );

        for slot in &mut self.viewport_slots {
            let dbg_buf = slot
                .debug_frag_buf
                .as_ref()
                .unwrap_or(&self.resources.debug_frag_sentinel_buf);
            slot.camera_bind_group = self.resources.create_camera_bind_group(
                device,
                &slot.camera_buf,
                &slot.clip_planes_buf,
                &slot.shadow_info_buf,
                &slot.clip_volume_buf,
                dbg_buf,
                "per_viewport_camera_bg",
            );
        }
    }

    /// Ensure a per-viewport slot exists for `viewport_index`.
    ///
    /// Creates a full `ViewportSlot` with independent uniform buffers for camera,
    /// clip planes, clip volume, shadow info, and grid. The camera bind group
    /// references this slot's per-viewport buffers plus shared scene-global
    /// resources. Slots are created lazily and never destroyed.
    fn ensure_viewport_slot(&mut self, device: &wgpu::Device, viewport_index: usize) {
        while self.viewport_slots.len() <= viewport_index {
            let camera_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_camera_buf"),
                size: std::mem::size_of::<CameraUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let clip_planes_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_clip_planes_buf"),
                size: std::mem::size_of::<ClipPlanesUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let clip_volume_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_clip_volume_buf"),
                size: std::mem::size_of::<ClipVolumesUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            // Seeded with the latest shadow atlas uniform rather than zeros:
            // prepare_scene_internal writes shadow info only to slots that
            // exist at that point, so a slot created later in the same frame
            // would otherwise render its first frame with zeroed cascade
            // matrices (NaN shadow UVs, everything shadowed).
            let shadow_info_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_shadow_info_buf"),
                size: std::mem::size_of::<ShadowAtlasUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: true,
            });
            shadow_info_buf
                .slice(..)
                .get_mapped_range_mut()
                .copy_from_slice(bytemuck::cast_slice(&[self
                    .shadow
                    .last_shadow_atlas_uniform]));
            shadow_info_buf.unmap();
            let grid_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_grid_buf"),
                size: std::mem::size_of::<GridUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });

            let camera_bind_group = self.resources.create_camera_bind_group(
                device,
                &camera_buf,
                &clip_planes_buf,
                &shadow_info_buf,
                &clip_volume_buf,
                &self.resources.debug_frag_sentinel_buf,
                "per_viewport_camera_bg",
            );

            let grid_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("vp_grid_bind_group"),
                layout: &self.resources.grid_bind_group_layout,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: grid_buf.as_entire_binding(),
                }],
            });

            // Per-viewport gizmo buffers (initial mesh: Translate, no hover, identity orientation).
            let (gizmo_verts, gizmo_indices) = crate::interaction::gizmo::build_gizmo_mesh(
                crate::interaction::gizmo::GizmoMode::Translate,
                crate::interaction::gizmo::GizmoAxis::None,
                glam::Quat::IDENTITY,
            );
            let gizmo_vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_gizmo_vertex_buf"),
                size: (std::mem::size_of::<crate::resources::Vertex>() * gizmo_verts.len().max(1))
                    as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: true,
            });
            gizmo_vertex_buffer
                .slice(..)
                .get_mapped_range_mut()
                .copy_from_slice(bytemuck::cast_slice(&gizmo_verts));
            gizmo_vertex_buffer.unmap();
            let gizmo_index_count = gizmo_indices.len() as u32;
            let gizmo_index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_gizmo_index_buf"),
                size: (std::mem::size_of::<u32>() * gizmo_indices.len().max(1)) as u64,
                usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: true,
            });
            gizmo_index_buffer
                .slice(..)
                .get_mapped_range_mut()
                .copy_from_slice(bytemuck::cast_slice(&gizmo_indices));
            gizmo_index_buffer.unmap();
            let gizmo_uniform = crate::interaction::gizmo::GizmoUniform {
                model: glam::Mat4::IDENTITY.to_cols_array_2d(),
            };
            let gizmo_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_gizmo_uniform_buf"),
                size: std::mem::size_of::<crate::interaction::gizmo::GizmoUniform>() as u64,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: true,
            });
            gizmo_uniform_buf
                .slice(..)
                .get_mapped_range_mut()
                .copy_from_slice(bytemuck::cast_slice(&[gizmo_uniform]));
            gizmo_uniform_buf.unmap();
            let gizmo_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("vp_gizmo_bind_group"),
                layout: &self.resources.gizmo_bind_group_layout,
                entries: &[wgpu::BindGroupEntry {
                    binding: 0,
                    resource: gizmo_uniform_buf.as_entire_binding(),
                }],
            });

            // Per-viewport axes vertex buffer (2048 vertices = enough for all axes geometry).
            let axes_vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("vp_axes_vertex_buf"),
                size: (std::mem::size_of::<crate::widgets::axes_indicator::AxesVertex>() * 2048)
                    as u64,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });

            self.viewport_slots.push(ViewportSlot {
                camera_buf,
                clip_planes_buf,
                clip_volume_buf,
                shadow_info_buf,
                grid_buf,
                camera_bind_group,
                grid_bind_group,
                hdr: None,
                debug_frag_buf: None,
                debug_frag_dims: (0, 0),
                outline_object_buffers: Vec::new(),
                splat_outline_buffers: Vec::new(),
                volume_outline_indices: Vec::new(),
                glyph_outline_indices: Vec::new(),
                tensor_glyph_outline_indices: Vec::new(),
                sprite_outline_indices: Vec::new(),
                raw_geom_outline_buffers: Vec::new(),
                screen_rect_outline_buffers: Vec::new(),
                implicit_outline_indices: Vec::new(),
                mc_outline_data: Vec::new(),
                streamtube_outline_items: Vec::new(),
                tube_outline_items: Vec::new(),
                ribbon_outline_items: Vec::new(),
                polyline_outline_indices: Vec::new(),
                xray_object_buffers: Vec::new(),
                constraint_line_buffers: Vec::new(),
                cap_buffers: Vec::new(),
                clip_plane_fill_buffers: Vec::new(),
                clip_plane_line_buffers: Vec::new(),
                axes_vertex_buffer,
                axes_vertex_count: 0,
                gizmo_uniform_buf,
                gizmo_bind_group,
                gizmo_vertex_buffer,
                gizmo_index_buffer,
                gizmo_index_count,
                sub_highlight: None,
                sub_highlight_generation: u64::MAX,
                dyn_res: None,
                hdr_callback: None,
            });
        }
    }

    // -----------------------------------------------------------------------
    // Multi-viewport public API
    // -----------------------------------------------------------------------

    /// Create a new viewport slot and return its handle.
    ///
    /// The returned [`ViewportId`] is stable for the lifetime of the renderer.
    /// Pass it to [`prepare_viewport`](Self::prepare_viewport),
    /// [`paint_viewport`](Self::paint_viewport), and
    /// [`render_viewport`](Self::render_viewport) each frame.
    ///
    /// Also set the viewport slot on the camera frame when building the
    /// [`FrameData`] for this viewport:
    /// ```rust,ignore
    /// let id = renderer.create_viewport(&device);
    /// let frame = FrameData {
    ///     camera: CameraFrame::from_camera(&cam, size).with_viewport_id(id),
    ///     ..Default::default()
    /// };
    /// ```
    pub fn create_viewport(&mut self, device: &wgpu::Device) -> ViewportId {
        let idx = self.viewport_slots.len();
        self.ensure_viewport_slot(device, idx);
        ViewportId(idx)
    }

    /// Release the heavy GPU texture memory (HDR targets, OIT, bloom, SSAO) held
    /// by `id`.
    ///
    /// The slot index is not reclaimed : future calls with this `ViewportId` will
    /// lazily recreate the texture resources as needed.  This is useful when a
    /// viewport is hidden or minimised and you want to reduce VRAM pressure without
    /// invalidating the handle.
    pub fn destroy_viewport(&mut self, id: ViewportId) {
        if let Some(slot) = self.viewport_slots.get_mut(id.0) {
            slot.hdr = None;
        }
    }

    /// Returns the owned-encoder rendering path.
    ///
    /// Use when you own the window loop and wgpu encoder (winit, raw wgpu).
    /// See [`OwnedPath`] for available methods.
    pub fn owned(&mut self) -> OwnedPath<'_> {
        OwnedPath { renderer: self }
    }

    /// Returns the pass-based rendering path.
    ///
    /// Use when a framework provides you with a render pass (eframe, iced).
    /// See [`PassPath`] for available methods.
    pub fn pass(&mut self) -> PassPath<'_> {
        PassPath { renderer: self }
    }

    /// Returns a read-only paint view for framework paint callbacks.
    ///
    /// Use this in callbacks where only a shared reference to the renderer is
    /// available (e.g. eframe's `CallbackTrait::paint` where `callback_resources`
    /// is `&CallbackResources`). Exposes only the paint methods, not prepare.
    pub fn pass_view(&self) -> PassView<'_> {
        PassView { renderer: self }
    }

    /// Prepare shared scene data.  Call **once per frame**, before any
    /// [`prepare_viewport`](Self::prepare_viewport) calls.
    ///
    /// `frame` provides the scene content (`frame.scene`) and the primary camera
    /// used for shadow cascade framing (`frame.camera`).  In a multi-viewport
    /// setup use any one viewport's `FrameData` here : typically the perspective
    /// view : as the shadow framing reference.
    ///
    /// `scene_effects` carries the scene-global effects: lighting, environment
    /// map, and compute filters.  Obtain it by constructing [`SceneEffects`]
    /// directly or via [`EffectsFrame::split`].
    pub(crate) fn prepare_scene(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        frame: &FrameData,
        scene_effects: &SceneEffects<'_>,
    ) {
        self.prepare_scene_internal(device, queue, frame, scene_effects);
    }

    /// Prepare per-viewport GPU state (camera, clip planes, overlays, axes).
    ///
    /// Call once per viewport per frame, **after** [`prepare_scene`](Self::prepare_scene).
    ///
    /// `id` must have been obtained from [`create_viewport`](Self::create_viewport).
    /// `frame.camera.viewport_index` must equal the slot for `id`; use
    /// [`CameraFrame::with_viewport_id`] when building the frame.
    pub(crate) fn prepare_viewport(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        id: ViewportId,
        frame: &FrameData,
    ) {
        debug_assert_eq!(
            frame.camera.viewport_index, id.0,
            "frame.camera.viewport_index ({}) must equal the ViewportId ({}); \
             use CameraFrame::with_viewport_id(id)",
            frame.camera.viewport_index, id.0,
        );
        let (_, viewport_fx) = frame.effects.split();
        self.prepare_viewport_internal(device, queue, frame, &viewport_fx);
    }

    /// Issue draw calls for `id` into a render pass with any lifetime.
    ///
    /// Identical to [`paint_viewport`](Self::paint_viewport) but accepts a render pass with a
    /// non-`'static` lifetime, making it usable from winit, iced, or raw wgpu where the encoder
    /// creates its own render pass.
    pub(crate) fn paint_viewport_to<'rp>(
        &self,
        render_pass: &mut wgpu::RenderPass<'rp>,
        id: ViewportId,
        frame: &FrameData,
    ) {
        let vp_idx = id.0;
        let camera_bg = self.viewport_camera_bind_group(vp_idx);
        let grid_bg = self.viewport_grid_bind_group(vp_idx);
        let vp_slot = self.viewport_slots.get(vp_idx);
        emit_draw_calls!(
            &self.resources,
            &mut *render_pass,
            frame,
            self.instancing.use_instancing,
            &self.instancing.batches,
            camera_bg,
            grid_bg,
            &self.compute_filter_results,
            vp_slot,
            &self.mesh_uniforms.wireframe_bind_groups,
            &self.mesh_uniforms.bind_groups
        );
        emit_scivis_draw_calls!(
            &self.resources,
            &mut *render_pass,
            &self.point_cloud_gpu_data,
            &self.glyph_gpu_data,
            &self.polyline_gpu_data,
            &self.volume_gpu_data,
            &self.streamtube_gpu_data,
            camera_bg,
            &self.tube_gpu_data,
            &self.image_slice_gpu_data,
            &self.tensor_glyph_gpu_data,
            &self.ribbon_gpu_data,
            &self.volume_surface_slice_gpu_data,
            &self.sprite_gpu_data,
            &self.mesh_instance_gpu_data,
            false
        );
        // Gaussian splats (alpha-blended, back-to-front sorted, no depth write).
        if !self.gaussian_splat_draw_data.is_empty() {
            if let Some(ref dual) = self.resources.gaussian_splat_pipeline {
                render_pass.set_pipeline(dual.for_format(false));
                render_pass.set_bind_group(0, camera_bg, &[]);
                for dd in &self.gaussian_splat_draw_data {
                    if dd.wireframe {
                        continue;
                    }
                    if let Some(set) = self.resources.gaussian_splat_store.get(dd.store_index) {
                        if let Some(Some(vp_sort)) = set.viewport_sort.get(dd.viewport_index) {
                            render_pass.set_bind_group(1, &vp_sort.render_bg, &[]);
                            render_pass.draw(0..6, 0..dd.count);
                        }
                    }
                }
            }
        }
        // TransparentVolumeMesh boundary wireframe overlay.
        if !self.mesh_uniforms.tvm_wireframe_draws.is_empty() {
            if let Some(ref tvm_bg) = self.mesh_uniforms.tvm_wireframe_bg {
                render_pass.set_bind_group(0, camera_bg, &[]);
                for mesh_id in &self.mesh_uniforms.tvm_wireframe_draws {
                    if let Some(mesh) = self.resources.mesh_store.get(*mesh_id) {
                        render_pass.set_pipeline(&self.resources.wireframe_pipeline);
                        render_pass.set_bind_group(2, &self.resources.deform.dummy_bind_group, &[]);
                        render_pass.set_bind_group(1, tvm_bg, &[]);
                        render_pass.set_vertex_buffer(0, mesh.vertex_buffer.slice(..));
                        render_pass.set_index_buffer(
                            mesh.edge_index_buffer.slice(..),
                            wgpu::IndexFormat::Uint32,
                        );
                        render_pass.draw_indexed(0..mesh.edge_index_count, 0, 0..1);
                    }
                }
            }
        }
        // Shadow atlas viewer overlay.
        if frame.effects.show_shadow_atlas {
            render_pass.set_pipeline(&self.resources.shadow_atlas_viewer_pipeline);
            render_pass.set_bind_group(0, &self.resources.shadow_atlas_viewer_bg, &[]);
            render_pass.draw(0..6, 0..1);
        }
    }

    /// Return a reference to the camera bind group for the given viewport slot.
    ///
    /// Falls back to `resources.camera_bind_group` if no per-viewport slot
    /// exists (e.g. in single-viewport mode before the first prepare call).
    fn viewport_camera_bind_group(&self, viewport_index: usize) -> &wgpu::BindGroup {
        self.viewport_slots
            .get(viewport_index)
            .map(|slot| &slot.camera_bind_group)
            .unwrap_or(&self.resources.camera_bind_group)
    }

    /// Return a reference to the grid bind group for the given viewport slot.
    ///
    /// Falls back to `resources.grid_bind_group` if no per-viewport slot exists.
    fn viewport_grid_bind_group(&self, viewport_index: usize) -> &wgpu::BindGroup {
        self.viewport_slots
            .get(viewport_index)
            .map(|slot| &slot.grid_bind_group)
            .unwrap_or(&self.resources.grid_bind_group)
    }

    /// Ensure the dyn-res intermediate render target exists for `vp_idx` at the
    /// given `scaled_size`, creating or recreating it when size changes.
    ///
    /// `surface_size` is the native output dimensions (used to size the upscale
    /// blit correctly). `ensure_dyn_res_pipeline` is called automatically.
    pub(crate) fn ensure_dyn_res_target(
        &mut self,
        device: &wgpu::Device,
        vp_idx: usize,
        scaled_size: [u32; 2],
        surface_size: [u32; 2],
    ) {
        self.resources.ensure_dyn_res_pipeline(device);
        let needs_create = match &self.viewport_slots[vp_idx].dyn_res {
            None => true,
            Some(dr) => dr.scaled_size != scaled_size || dr.surface_size != surface_size,
        };
        if needs_create {
            let target = self
                .resources
                .create_dyn_res_target(device, scaled_size, surface_size);
            self.viewport_slots[vp_idx].dyn_res = Some(target);
        }
    }

    /// Ensure per-viewport HDR state exists for `viewport_index` at dimensions `w`x`h`.
    ///
    /// Calls `ensure_hdr_shared` once to initialise shared pipelines/BGLs/samplers, then
    /// lazily creates or resizes the `ViewportHdrState` inside the slot. Idempotent: if the
    /// slot already has HDR state at the correct size nothing is recreated.
    pub(crate) fn ensure_viewport_hdr(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        viewport_index: usize,
        w: u32,
        h: u32,
        ssaa_factor: u32,
        render_scale: f32,
    ) {
        let format = self.resources.target_format;
        // Ensure shared infrastructure (pipelines, BGLs, samplers) exists.
        self.resources.ensure_hdr_shared(device, queue, format);
        // When render_scale < 1.0, the HDR upscale path needs the dyn_res
        // pipeline and sampler for the final upscale-blit to output resolution.
        if render_scale < 1.0 - 0.001 {
            self.resources.ensure_dyn_res_pipeline(device);
        }
        // Compute the scene-resolution render target size.
        let scale = render_scale.clamp(0.1, 1.0);
        let scene_w = ((w as f32) * scale).round() as u32;
        let scene_h = ((h as f32) * scale).round() as u32;
        // Ensure the slot exists.
        self.ensure_viewport_slot(device, viewport_index);
        let slot = &mut self.viewport_slots[viewport_index];
        // Create or resize the per-viewport HDR state.
        let needs_create = match &slot.hdr {
            None => true,
            Some(s) => {
                s.output_size != [w, h]
                    || s.scene_size != [scene_w.max(1), scene_h.max(1)]
                    || s.ssaa_factor != ssaa_factor
            }
        };
        if needs_create {
            slot.hdr = Some(self.resources.create_hdr_viewport_state(
                device,
                queue,
                format,
                w,
                h,
                scene_w.max(1),
                scene_h.max(1),
                ssaa_factor,
            ));
        }
    }
}