graphics 0.5.12

A 3D rendering engine for rust programs, with GUI integration
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
//! This module contains the core part of interaction with the graphics API. It is tied closely
//! to the WGPU library. We set up pipelines, populate vertex and index buffers, define shaders,
//! and create render passes.
//!
//! See [Official WGPU examples](https://github.com/gfx-rs/wgpu/tree/master/wgpu/examples)
//! See [Bevy Garphics](https://github.com/bevyengine/bevy/blob/main/crates/bevy_render) for
//! a full graphics engine example that uses Wgpu.
//! https://sotrh.github.io/learn-wgpu/
//!
//! https://github.com/sotrh/learn-wgpu/tree/master/code/intermediate/tutorial12-camera/src
//! https://github.com/gfx-rs/wgpu/tree/master/wgpu/examples/shadow
//!
//! 2022-08-21: https://github.com/gfx-rs/wgpu/blob/master/wgpu/examples/cube/main.rs

use std::{collections::HashSet, sync::Arc, time::Duration};

use egui::Context;
use lin_alg::f32::{Mat4, Vec3};
use wgpu::{
    self, BindGroup, BindGroupLayout, BindingType, BlendState, Buffer, BufferBindingType,
    BufferUsages, CommandEncoder, CommandEncoderDescriptor, DepthStencilState, Device, Face,
    FragmentState, Queue, RenderPass, RenderPassDepthStencilAttachment, RenderPassDescriptor,
    RenderPipeline, ShaderStages, StoreOp, SurfaceConfiguration, SurfaceTexture, TextureDescriptor,
    TextureView, VertexBufferLayout, VertexState,
    util::{BufferInitDescriptor, DeviceExt},
};
use winit::{
    event::{DeviceEvent, WindowEvent},
    window::Window,
};

use crate::{
    camera::CAMERA_SIZE,
    gauss::{
        CAM_BASIS_SIZE, CameraBasis, GAUSS_INST_LAYOUT, GaussianInstance, QUAD_VERTEX_LAYOUT,
        QUAD_VERTICES,
    },
    gui::GuiState,
    input::{self, InputsCommanded},
    system::{COLOR_FORMAT, DEPTH_FORMAT, process_engine_updates},
    text_overlay::draw_text_overlay,
    texture::Texture,
    types::{
        AmbientOcclusion, ControlScheme, EngineUpdates, GraphicsSettings, INSTANCE_LAYOUT,
        INSTANCE_SIZE, InputSettings, Instance, Scene, UiSettings, VERTEX_LAYOUT,
    },
    viewport_rect,
};

pub const UP_VEC: Vec3 = Vec3 {
    x: 0.,
    y: 1.,
    z: 0.,
};
pub const RIGHT_VEC: Vec3 = Vec3 {
    x: 1.,
    y: 0.,
    z: 0.,
};
pub const FWD_VEC: Vec3 = Vec3 {
    x: 0.,
    y: 0.,
    z: 1.,
};

/// We use this to define the extent of entity updates, and its effect on the instance buffer.
/// For example, rebuild all entities, or update specific ones in-place.
#[derive(Clone, Debug, PartialEq, Default)]
pub enum EntityUpdate {
    #[default]
    None,
    /// Performs a complete rebuild of the instance buffer. This is a safe default
    /// whenever entities changes, but updating specific IDs or classes can be more
    /// efficient.
    All,
    /// Update specific classes in place, without changing the instance buffer size.
    Classes(Vec<u32>),
    /// Update specific IDs in place, without changing the instance buffer size.
    Ids(Vec<u32>),
    /// A range of start and end indexes.
    Indexes((usize, usize)),
    /// Append this many to the end
    Append(usize),
}

impl EntityUpdate {
    pub fn push_class(&mut self, class: u32) {
        match self {
            EntityUpdate::All => (),
            // todo: Support for updating both classes and IDs at once.
            EntityUpdate::Classes(v) => v.push(class),
            _ => *self = EntityUpdate::Classes(vec![class]),
        }
    }

    pub fn push_id(&mut self, id: u32) {
        match self {
            EntityUpdate::All => (),
            // todo: Support for updating both classes and IDs at once.
            EntityUpdate::Ids(v) => v.push(id),
            _ => *self = EntityUpdate::Ids(vec![id]),
        }
    }
}

/// Code related to our specific engine. Buffers, texture data etc.
pub(crate) struct GraphicsState {
    pub vertex_buf: Buffer,
    // pub vertex_buf_transparent: Buffer,
    pub vertex_buf_quad: Buffer, // For gaussians.
    pub index_buf: Buffer,
    // pub index_buf_transparent: Buffer,
    instance_buf: Buffer,
    instance_buf_transparent: Buffer,
    instance_buf_gauss: Buffer,
    pub bind_groups: BindGroupData,
    pub camera_buf: Buffer,
    /// Separate camera buffer for the depth-aware halo prepass (halo_expansion > 0).
    camera_buf_halo: Buffer,
    /// Bind group pointing at camera_buf_halo, used during the halo prepass.
    bind_group_cam_halo: wgpu::BindGroup,
    pub cam_basis_buf: Buffer, // For gaussians
    lighting_buf: Buffer,
    /// For opaque meshes
    pub pipeline_mesh: RenderPipeline, // todo: Move to renderer.
    /// For transparent meshes: Disable back-culling.
    pub pipeline_mesh_transparent: RenderPipeline, // todo: Move to renderer.
    /// We use this two-pipeline approach for transparent meshes for rendering ones that
    /// are transparent, and double-sided.
    pub pipeline_mesh_transparent_back: RenderPipeline, // todo: Move to renderer.
    pub pipeline_gauss: RenderPipeline, // todo: Move to renderer.
    /// Depth-only, front-face-culled pipeline for the halo prepass.
    pipeline_halo: RenderPipeline,
    pub depth_texture: Texture,
    pub msaa_texture: Option<TextureView>, // MSAA Multisampled texture
    pub inputs_commanded: InputsCommanded,
    // staging_belt: wgpu::util::StagingBelt, // todo: Do we want this? Probably in sys, not here.
    pub scene: Scene,
    mesh_mappings: Vec<(i32, u32, u32)>,
    mesh_mappings_transparent: Vec<(i32, u32, u32)>,
    pub window: Arc<Window>,
    /// World-space expansion (along normals) used in the halo prepass. 0 = disabled.
    pub halo_expansion: f32,
    /// 1-sample depth texture written by the contour depth prepass, sampled by the overlay.
    pub depth_texture_contour: Texture,
    /// Depth-only pipeline for populating depth_texture_contour (1-sample, back-face cull).
    pipeline_contour_depth: RenderPipeline,
    /// Full-screen pipeline that reads depth_texture_contour and overlays contour lines.
    pipeline_contour_overlay: RenderPipeline,
    /// Bind group for the contour overlay: depth texture + uniform buffer.
    pub bind_group_contour: wgpu::BindGroup,
    /// Layout reused when recreating the contour bind group on resize.
    pub layout_contour: wgpu::BindGroupLayout,
    pub contour_uniform_buf: Buffer,
    pub depth_revealing: f32,
    pub intersection_revealing: f32,
    /// 0.0 = SSAO disabled; > 0 enables the SSAO overlay.
    pub ssao_strength: f32,
    /// Current MSAA sample count, kept in sync so resize and MSAA changes are consistent.
    pub msaa_samples: u32,
    /// When set, the event loop will recreate MSAA-dependent resources (pipelines, textures,
    /// GUI renderer) before the next frame, then clear this field.
    pub pending_msaa: Option<u32>,
    /// Cached surface configuration — updated on resize, used for resource recreation.
    pub surface_cfg: SurfaceConfiguration,
    /// Stored mesh shader (needed to recreate MSAA-dependent pipelines without re-parsing).
    shader_mesh: wgpu::ShaderModule,
    /// Stored Gaussian shader (same reason).
    shader_gauss: wgpu::ShaderModule,
    /// Full-screen SSAO overlay pipeline.
    pipeline_ssao: RenderPipeline,
    /// Bind-group layout for the SSAO pass (depth tex + uniform buf).
    pub layout_ssao: wgpu::BindGroupLayout,
    /// Bind group referencing depth_texture_contour and ssao_uniform_buf.
    pub bind_group_ssao: wgpu::BindGroup,
    /// Uniform buffer written every frame when SSAO is active.
    pub ssao_uniform_buf: Buffer,
}

impl GraphicsState {
    pub(crate) fn new(
        device: &Device,
        surface_cfg: &SurfaceConfiguration,
        mut scene: Scene,
        window: Arc<Window>,
        msaa_samples: u32,
    ) -> Self {
        let vertex_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Vertex buffer"),
            contents: &[], // Populated later.
            usage: BufferUsages::VERTEX,
        });

        let mut quad_bytes = Vec::with_capacity(QUAD_VERTICES.len() * 8);
        for q in QUAD_VERTICES {
            quad_bytes.extend_from_slice(q.to_bytes().as_slice());
        }

        let vertex_buf_quad = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Gauss quadVertex buffer"),
            contents: &quad_bytes,
            usage: BufferUsages::VERTEX,
        });

        let index_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Index buffer"),
            contents: &[], // Populated later.
            usage: BufferUsages::INDEX,
        });

        scene.camera.update_proj_mat();

        let cam_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Camera buffer"),
            contents: &scene.camera.to_bytes(),
            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
        });

        // for gauss
        let cam_basis_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("camera basis"),
            size: size_of::<CameraBasis>() as wgpu::BufferAddress,
            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let lighting_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Lighting buffer"),
            contents: &scene.lighting.to_bytes(),
            // We use a storage buffer, since our lighting size is unknown by the shader;
            // this is due to the dynamic-sized point light array.
            usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
        });
        //

        let bind_groups = create_bindgroups(device, &cam_buf, &cam_basis_buf, &lighting_buf);

        // Halo prepass resources: a separate camera buffer (halo_expansion = 0 until
        // apply_graphics_settings writes the real value).
        let cam_halo_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Camera halo buffer"),
            contents: &scene.camera.to_bytes(),
            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
        });
        let bind_group_cam_halo = device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &bind_groups.layout_cam,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: cam_halo_buf.as_entire_binding(),
            }],
            label: Some("Camera halo bind group"),
        });

        let depth_texture =
            Texture::create_depth_texture(device, surface_cfg, "Depth texture", msaa_samples);

        let shader_mesh = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Graphics shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
        });

        let pipeline_layout_mesh = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Render pipeline layout"),
            bind_group_layouts: &[&bind_groups.layout_cam, &bind_groups.layout_lighting],
            push_constant_ranges: &[],
        });

        let depth_stencil_mesh = DepthStencilState {
            format: DEPTH_FORMAT,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        };

        // todo: You should probably, eventually, make two passes for meshes. One for
        // opaque objects, with no blending (blend_state = None), then a second pass
        // for transparent objects. You would set depth to write only, for opaque objects,
        // and read only, for alpha blending transparent meshes.

        let pipeline_mesh = create_render_pipeline(
            device,
            &pipeline_layout_mesh,
            shader_mesh.clone(),
            surface_cfg,
            msaa_samples,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            Some(depth_stencil_mesh.clone()),
            // Some(depth_stencil_mesh),
            None,
            Some(Face::Back),
            "Render pipeline mesh opaque",
        );

        // Separate mesh for transparent meshes, so we disable back culling.
        let pipeline_mesh_transparent = create_render_pipeline(
            device,
            &pipeline_layout_mesh,
            shader_mesh.clone(),
            surface_cfg,
            msaa_samples,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            // Some(depth_stencil_mesh_transparent.clone()),
            Some(depth_stencil_mesh.clone()),
            Some(BlendState::ALPHA_BLENDING),
            Some(Face::Back),
            "Render pipeline mesh transparent",
        );

        let pipeline_mesh_transparent_back = create_render_pipeline(
            device,
            &pipeline_layout_mesh,
            shader_mesh.clone(),
            surface_cfg,
            msaa_samples,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            // Some(depth_stencil_mesh_transparent),
            Some(depth_stencil_mesh.clone()),
            Some(BlendState::ALPHA_BLENDING),
            Some(Face::Front),
            "Render pipeline mesh transparent – backfaces",
        );

        // Halo prepass: depth-only, front-face culled, inflated by halo_expansion in vs.
        // Only needs the camera bind group (no fragment stage → no lighting needed).
        let pipeline_layout_halo = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Halo pipeline layout"),
            bind_group_layouts: &[&bind_groups.layout_cam, &bind_groups.layout_lighting],
            push_constant_ranges: &[],
        });
        let pipeline_halo = create_render_pipeline_depth_only(
            device,
            &pipeline_layout_halo,
            shader_mesh.clone(),
            msaa_samples,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            depth_stencil_mesh.clone(),
        );

        // ── Contour lines ────────────────────────────────────────────────────────────
        // A 1-sample depth texture populated by a prepass; always 1-sample so it can
        // be bound as texture_depth_2d in the overlay shader regardless of MSAA setting.
        let depth_texture_contour =
            Texture::create_depth_texture(device, surface_cfg, "Depth texture contour", 1);

        // Prepass pipeline: same shader, depth-only (fragment: None), 1-sample, back-face cull.
        let pipeline_contour_depth = {
            let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Contour depth prepass layout"),
                bind_group_layouts: &[&bind_groups.layout_cam],
                push_constant_ranges: &[],
            });
            create_contour_depth_pipeline(
                device,
                &layout,
                shader_mesh.clone(),
                &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            )
        };

        // Overlay pipeline: full-screen triangle, alpha-blended, no depth attachment.
        let shader_contour = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Contour overlay shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shader_contour.wgsl").into()),
        });
        let layout_contour = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("Contour bind group layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Depth,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: wgpu::BufferSize::new(32),
                    },
                    count: None,
                },
            ],
        });
        let contour_uniform_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Contour uniform buffer"),
            contents: &contour_uniform_bytes(0.1, 0., 0., scene.camera.near, scene.camera.far),
            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
        });
        let bind_group_contour = create_contour_bind_group(
            device,
            &layout_contour,
            &depth_texture_contour.view,
            &contour_uniform_buf,
        );
        let pipeline_contour_overlay = {
            let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Contour overlay pipeline layout"),
                bind_group_layouts: &[&layout_contour],
                push_constant_ranges: &[],
            });
            create_contour_overlay_pipeline(device, &layout, shader_contour, surface_cfg)
        };
        // ── End contour ──────────────────────────────────────────────────────────────

        // ── SSAO ─────────────────────────────────────────────────────────────────────
        let shader_ssao = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("SSAO shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shader_ssao.wgsl").into()),
        });
        let layout_ssao = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("SSAO bind group layout"),
            entries: &[
                // Binding 0: 1-sample depth texture from geometry prepass.
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Depth,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                // Binding 1: SSAO uniform buffer.
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: wgpu::BufferSize::new(SSAO_UNIFORM_SIZE as u64),
                    },
                    count: None,
                },
            ],
        });
        let ssao_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("SSAO uniform buffer"),
            size: SSAO_UNIFORM_SIZE as wgpu::BufferAddress,
            usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let bind_group_ssao = create_ssao_bind_group(
            device,
            &layout_ssao,
            &depth_texture_contour.view,
            &ssao_uniform_buf,
        );
        let pipeline_ssao = {
            let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("SSAO pipeline layout"),
                bind_group_layouts: &[&layout_ssao],
                push_constant_ranges: &[],
            });
            create_ssao_pipeline(device, &layout, shader_ssao, surface_cfg)
        };
        // ── End SSAO ─────────────────────────────────────────────────────────────────

        // We initialize instances, the instance buffer and mesh mappings in `setup_entities`.
        // let instances = Vec::new();
        let instance_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Instance buffer"),
            contents: &[], // empty on init
            usage: BufferUsages::VERTEX,
        });

        let instance_buf_transparent = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Instance buffer transparent"),
            contents: &[], // empty on init
            usage: BufferUsages::VERTEX,
        });

        let shader_gauss = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("Graphics shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shader_gauss.wgsl").into()),
        });

        let pipeline_layout_gauss =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Gaussian pipeline layout"),
                bind_group_layouts: &[&bind_groups.layout_cam_gauss],
                push_constant_ranges: &[],
            });

        let depth_stencil_gauss = Some(DepthStencilState {
            format: DEPTH_FORMAT,
            // Seems to be required to be false to prevent gaussians from popping in and out.
            depth_write_enabled: false,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        });

        let pipeline_gauss = create_render_pipeline(
            device,
            &pipeline_layout_gauss,
            shader_gauss.clone(),
            surface_cfg,
            msaa_samples,
            &[QUAD_VERTEX_LAYOUT, GAUSS_INST_LAYOUT],
            depth_stencil_gauss,
            // todo These two blend styles approaches produce noticibly different results. Experiment.
            Some(BlendState::ALPHA_BLENDING),
            None,
            // Some(BlendState {
            //     color: BlendComponent {
            //         src_factor: BlendFactor::One,
            //         dst_factor: BlendFactor::One,
            //         operation: BlendOperation::Add,
            //     },
            //     alpha: BlendComponent {
            //         src_factor: BlendFactor::One,
            //         dst_factor: BlendFactor::One,
            //         operation: BlendOperation::Add,
            //     },
            // }),
            "Render pipeline gaussian",
        );

        let instance_gauss_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Gaussian Instance buffer"),
            contents: &[], // empty on init
            usage: BufferUsages::VERTEX,
        });

        // Placeholder value
        let mesh_mappings = Vec::new();
        let mesh_mappings_transparent = Vec::new();

        // todo: Logical (scaling by device?) vs physical pixels
        // let window_size = winit::dpi::LogicalSize::new(scene.window_size.0, scene.window_size.1);
        window.set_title(&scene.window_title);

        let msaa_texture = if msaa_samples > 1 {
            Some(Self::create_msaa_texture(device, surface_cfg, msaa_samples))
        } else {
            None
        };

        let mut result = Self {
            vertex_buf,
            vertex_buf_quad,
            index_buf,
            instance_buf,
            instance_buf_transparent,
            instance_buf_gauss: instance_gauss_buf,
            bind_groups,
            camera_buf: cam_buf,
            camera_buf_halo: cam_halo_buf,
            bind_group_cam_halo,
            cam_basis_buf,
            lighting_buf,
            pipeline_mesh,
            pipeline_mesh_transparent,
            pipeline_mesh_transparent_back,
            pipeline_gauss,
            pipeline_halo,
            depth_texture_contour,
            pipeline_contour_depth,
            pipeline_contour_overlay,
            bind_group_contour,
            layout_contour,
            contour_uniform_buf,
            depth_revealing: 0.,
            intersection_revealing: 0.,
            ssao_strength: 0.,
            msaa_samples,
            pending_msaa: None,
            surface_cfg: surface_cfg.clone(),
            shader_mesh,
            shader_gauss,
            pipeline_ssao,
            layout_ssao,
            bind_group_ssao,
            ssao_uniform_buf,
            depth_texture,
            // staging_belt: wgpu::util::StagingBelt::new(0x100),
            scene,
            inputs_commanded: Default::default(),
            mesh_mappings,
            mesh_mappings_transparent,
            window,
            msaa_texture,
            halo_expansion: 0.,
        };

        result.setup_vertices_indices(device);
        result.setup_entities(device);

        result
    }

    pub(crate) fn create_msaa_texture(
        device: &Device,
        surface_cfg: &SurfaceConfiguration,
        sample_count: u32,
    ) -> TextureView {
        let msaa_texture = device.create_texture(&TextureDescriptor {
            label: Some("Multisampled Texture"),
            size: wgpu::Extent3d {
                width: surface_cfg.width,
                height: surface_cfg.height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count,
            dimension: wgpu::TextureDimension::D2,
            format: surface_cfg.format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });

        msaa_texture.create_view(&wgpu::TextureViewDescriptor::default())
    }

    pub(crate) fn handle_input_device(
        &mut self,
        event: &DeviceEvent,
        input_settings: &InputSettings,
    ) {
        match input_settings.control_scheme {
            ControlScheme::FreeCamera | ControlScheme::Arc { center: _ } => {
                input::add_input_cmd_device(
                    event,
                    &mut self.inputs_commanded,
                    input_settings.device_events_for_cam_controls,
                )
            }
            _ => unimplemented!(),
        }
    }

    pub(crate) fn handle_input_window(
        &mut self,
        event: &WindowEvent,
        input_settings: &InputSettings,
    ) {
        match input_settings.control_scheme {
            ControlScheme::FreeCamera | ControlScheme::Arc { center: _ } => {
                input::add_input_cmd_window(
                    event,
                    &mut self.inputs_commanded,
                    input_settings.device_events_for_cam_controls,
                )
            }
            _ => unimplemented!(),
        }
    }

    /// Updates meshes.
    pub(crate) fn setup_vertices_indices(&mut self, device: &Device) {
        let mut vertices = Vec::new();
        let mut indices = Vec::new();

        for mesh in &self.scene.meshes {
            for vertex in &mesh.vertices {
                vertices.push(vertex)
            }

            for index in &mesh.indices {
                indices.push(index);
            }
        }

        // Convert the vertex and index data to u8 buffers.
        let mut vertex_data = Vec::new();
        for vertex in vertices {
            for byte in vertex.to_bytes() {
                vertex_data.push(byte);
            }
        }

        let mut index_data = Vec::new();
        for index in indices {
            let bytes = index.to_ne_bytes();
            index_data.push(bytes[0]);
            index_data.push(bytes[1]);
            index_data.push(bytes[2]);
            index_data.push(bytes[3]);
        }

        // We can't update using a queue due to buffer size mismatches.
        let vertex_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Vertex buffer"),
            contents: &vertex_data,
            usage: BufferUsages::VERTEX,
        });

        let index_buf = device.create_buffer_init(&BufferInitDescriptor {
            label: Some("Index buffer"),
            contents: &index_data,
            usage: BufferUsages::INDEX,
        });

        self.vertex_buf = vertex_buf;
        // Note: Gauss vertex buf is static; we set it up at init, and don't change it.

        self.index_buf = index_buf;
    }

    /// Replace instance buffer entries directly for specific entities. This is cheaper than
    /// rebuilding the instance buffers whenever an entitity changes. This only supports in-place
    /// changes; no adding or removing instances.
    pub(crate) fn replace_instance_entries(
        &mut self,
        queue: &Queue,
        device: &Device,
        update_type: &EntityUpdate,
    ) {
        let classes_or_ids: HashSet<_> = match update_type {
            EntityUpdate::Classes(v) | EntityUpdate::Ids(v) => v.iter().copied().collect(),
            _ => HashSet::new(), // Unused
        };

        let mut needs_full_rebuild = false;

        let ents_to_update = match update_type {
            EntityUpdate::Indexes((start, end)) => &self.scene.entities[*start..*end],
            _ => &self.scene.entities,
        };

        for ent in ents_to_update {
            match update_type {
                EntityUpdate::Classes(_) => {
                    if !classes_or_ids.contains(&ent.class) {
                        continue;
                    }
                }
                EntityUpdate::Ids(_) => {
                    if !classes_or_ids.contains(&ent.id) {
                        continue;
                    }
                }
                _ => (),
            };

            let Some(slot) = ent.buf_i else {
                needs_full_rebuild = true;
                break;
            };

            // If opacity bucket changed since last rebuild, our slot is invalid → full rebuild.
            let now_is_transparent = ent.opacity < 0.99;
            if now_is_transparent != ent.buf_is_transparent {
                needs_full_rebuild = true;
                break;
            }

            let instance: Instance = ent.into();
            let bytes = instance.to_bytes();
            let byte_offset = (slot * INSTANCE_SIZE) as u64;

            if ent.buf_is_transparent {
                queue.write_buffer(&self.instance_buf_transparent, byte_offset, &bytes);
            } else {
                queue.write_buffer(&self.instance_buf, byte_offset, &bytes);
            }
        }

        if needs_full_rebuild {
            // todo: Put back A/R to help diagnose problems.
            // println!("Performing a full entity rebuild; unable to update in-place");
            self.setup_entities(device);
        }
    }

    /// Sets up entities (And the associated instance buffer), but doesn't change
    /// meshes, lights, or the camera. The vertex and index buffers aren't changed; only the instances.
    /// This rebuilds the instance buffers from scratch from entities.
    pub(crate) fn setup_entities(&mut self, device: &Device) {
        let mut instances = Vec::new();
        let mut instances_transparent: Vec<Instance> = Vec::new();
        let mut instances_gauss = Vec::with_capacity(self.scene.gaussians.len());

        let mut mesh_mappings = Vec::new();
        let mut mesh_mappings_transparent = Vec::new();

        let mut vertex_start_this_mesh = 0;

        let mut instance_start_this_mesh = 0;
        let mut instance_start_this_mesh_transparent = 0;

        let mut i_opaque = 0;
        let mut i_transparent = 0;

        // Build mesh-based instances.
        for (i, mesh) in self.scene.meshes.iter().enumerate() {
            let mut instance_count_this_mesh = 0;
            let mut instance_count_this_mesh_transparent = 0;

            for entity in self.scene.entities.iter_mut().filter(|e| e.mesh == i) {
                let instance: Instance = (&*entity).into();

                if entity.opacity < 0.99 {
                    instances_transparent.push(instance);
                    instance_count_this_mesh_transparent += 1;

                    // For our in-place replacement system.
                    entity.buf_i = Some(i_transparent);
                    entity.buf_is_transparent = true;
                    i_transparent += 1;
                } else {
                    instances.push(instance);
                    instance_count_this_mesh += 1;

                    entity.buf_i = Some(i_opaque);
                    entity.buf_is_transparent = false;
                    i_opaque += 1;
                }
            }

            mesh_mappings.push((
                vertex_start_this_mesh,
                instance_start_this_mesh,
                instance_count_this_mesh,
            ));

            mesh_mappings_transparent.push((
                vertex_start_this_mesh,
                instance_start_this_mesh_transparent,
                instance_count_this_mesh_transparent,
            ));

            vertex_start_this_mesh += mesh.vertices.len() as i32;

            instance_start_this_mesh += instance_count_this_mesh;
            instance_start_this_mesh_transparent += instance_count_this_mesh_transparent;
        }

        self.mesh_mappings = mesh_mappings;
        self.mesh_mappings_transparent = mesh_mappings_transparent;

        // Build gaussian-based instances.
        for gauss in &self.scene.gaussians {
            instances_gauss.push(gauss.to_instance());
        }

        self.instance_buf = setup_instance_buf(device, &instances, "Instance buffer");
        self.instance_buf_transparent = setup_instance_buf(
            device,
            &instances_transparent,
            "Instance buffer transparent",
        );
        self.instance_buf_gauss =
            setup_instance_buf_gauss(device, &instances_gauss, "Instance buffer Gaussian");
    }

    pub(crate) fn update_camera(&mut self, queue: &Queue) {
        queue.write_buffer(&self.camera_buf, 0, &self.scene.camera.to_bytes());

        if self.halo_expansion > 0.0 {
            let mut halo_cam = self.scene.camera.clone();
            halo_cam.halo_expansion = self.halo_expansion;
            queue.write_buffer(&self.camera_buf_halo, 0, &halo_cam.to_bytes());
        }

        // Required due to not being able to take inverse of 4x4 matrices in shaders?
        if !self.scene.gaussians.is_empty() {
            queue.write_buffer(
                &self.cam_basis_buf,
                0,
                &CameraBasis::new(self.scene.camera.view_mat()).to_bytes(),
            );
        }
    }

    pub(crate) fn update_lighting(&mut self, queue: &Queue) {
        queue.write_buffer(&self.lighting_buf, 0, &self.scene.lighting.to_bytes());
    }

    /// Write SSAO uniform buffer from the current camera state.
    pub(crate) fn update_ssao_uniforms(&self, queue: &Queue) {
        let proj_view = self.scene.camera.proj_mat.clone() * self.scene.camera.view_mat();
        let proj_view_inv = proj_view.inverse().unwrap_or_else(Mat4::new_identity);
        let bytes = ssao_uniform_bytes(
            &proj_view,
            &proj_view_inv,
            self.scene.camera.position,
            self.scene.camera.near,
            self.scene.camera.far,
            0.5,   // world-space sample radius
            0.001, // depth bias (prevents self-occlusion)
            self.ssao_strength,
        );
        queue.write_buffer(&self.ssao_uniform_buf, 0, &bytes);
    }

    /// Apply a complete `GraphicsSettings` snapshot to this state.
    /// Shared by init (via `system.rs`) and runtime updates (via `process_engine_updates`).
    /// MSAA is intentionally excluded – it requires pipeline recreation and is
    /// handled separately via `pending_msaa` / `apply_msaa_change`.
    pub(crate) fn apply_graphics_settings(&mut self, settings: &GraphicsSettings, queue: &Queue) {
        // ── Edge cueing ───────────────────────────────────────────────────────
        let new_edge = settings.edge_cueing.unwrap_or(0.0);
        if self.scene.camera.edge_cueing != new_edge {
            self.scene.camera.edge_cueing = new_edge;
            self.update_camera(queue);
        }

        // ── Depth-aware halos ─────────────────────────────────────────────────
        let new_halo = settings.depth_aware_halos.unwrap_or(0.0);
        if self.halo_expansion != new_halo {
            self.halo_expansion = new_halo;
            self.update_camera(queue);
        }

        // ── Contour lines ─────────────────────────────────────────────────────
        let new_depth_rev = settings.depth_revealing_contour_lines.unwrap_or(0.0);
        let new_isect_rev = settings.intersection_revealing_contour_lines.unwrap_or(0.0);
        if self.depth_revealing != new_depth_rev || self.intersection_revealing != new_isect_rev {
            self.depth_revealing = new_depth_rev;
            self.intersection_revealing = new_isect_rev;
            queue.write_buffer(
                &self.contour_uniform_buf,
                0,
                &contour_uniform_bytes(
                    0.1,
                    new_depth_rev,
                    new_isect_rev,
                    self.scene.camera.near,
                    self.scene.camera.far,
                ),
            );
        }

        // ── Ambient occlusion (SSAO) ──────────────────────────────────────────
        self.ssao_strength = match settings.ambient_occlusion {
            AmbientOcclusion::Ssao => 1.5,
            _ => 0.0,
        };
    }

    /// Recreate all MSAA-dependent resources after a sample-count change.
    /// Call this from the event loop (which also has access to GuiState for its renderer).
    pub(crate) fn apply_msaa_change(&mut self, device: &Device) {
        let new_msaa = self.msaa_samples;

        self.depth_texture =
            Texture::create_depth_texture(device, &self.surface_cfg, "Depth texture", new_msaa);
        self.msaa_texture = if new_msaa > 1 {
            Some(Self::create_msaa_texture(
                device,
                &self.surface_cfg,
                new_msaa,
            ))
        } else {
            None
        };

        let depth_stencil_mesh = DepthStencilState {
            format: DEPTH_FORMAT,
            depth_write_enabled: true,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        };

        let pipeline_layout_mesh = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Render pipeline layout"),
            bind_group_layouts: &[
                &self.bind_groups.layout_cam,
                &self.bind_groups.layout_lighting,
            ],
            push_constant_ranges: &[],
        });

        self.pipeline_mesh = create_render_pipeline(
            device,
            &pipeline_layout_mesh,
            self.shader_mesh.clone(),
            &self.surface_cfg,
            new_msaa,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            Some(depth_stencil_mesh.clone()),
            None,
            Some(Face::Back),
            "Render pipeline mesh opaque",
        );
        self.pipeline_mesh_transparent = create_render_pipeline(
            device,
            &pipeline_layout_mesh,
            self.shader_mesh.clone(),
            &self.surface_cfg,
            new_msaa,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            Some(depth_stencil_mesh.clone()),
            Some(BlendState::ALPHA_BLENDING),
            Some(Face::Back),
            "Render pipeline mesh transparent",
        );
        self.pipeline_mesh_transparent_back = create_render_pipeline(
            device,
            &pipeline_layout_mesh,
            self.shader_mesh.clone(),
            &self.surface_cfg,
            new_msaa,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            Some(depth_stencil_mesh.clone()),
            Some(BlendState::ALPHA_BLENDING),
            Some(Face::Front),
            "Render pipeline mesh transparent – backfaces",
        );

        let pipeline_layout_halo = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Halo pipeline layout"),
            bind_group_layouts: &[
                &self.bind_groups.layout_cam,
                &self.bind_groups.layout_lighting,
            ],
            push_constant_ranges: &[],
        });
        self.pipeline_halo = create_render_pipeline_depth_only(
            device,
            &pipeline_layout_halo,
            self.shader_mesh.clone(),
            new_msaa,
            &[VERTEX_LAYOUT, INSTANCE_LAYOUT],
            depth_stencil_mesh,
        );

        let depth_stencil_gauss = Some(DepthStencilState {
            format: DEPTH_FORMAT,
            depth_write_enabled: false,
            depth_compare: wgpu::CompareFunction::Less,
            stencil: wgpu::StencilState::default(),
            bias: wgpu::DepthBiasState::default(),
        });
        let pipeline_layout_gauss =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Gaussian pipeline layout"),
                bind_group_layouts: &[&self.bind_groups.layout_cam_gauss],
                push_constant_ranges: &[],
            });
        self.pipeline_gauss = create_render_pipeline(
            device,
            &pipeline_layout_gauss,
            self.shader_gauss.clone(),
            &self.surface_cfg,
            new_msaa,
            &[QUAD_VERTEX_LAYOUT, GAUSS_INST_LAYOUT],
            depth_stencil_gauss,
            Some(BlendState::ALPHA_BLENDING),
            None,
            "Render pipeline gaussian",
        );
    }

    fn setup_render_pass<'a>(
        &mut self,
        encoder: &'a mut CommandEncoder,
        output_view: &TextureView,
        win_width: u32,
        win_height: u32,
        ui_settings: &UiSettings,
        ui_size: (f32, f32),
        pixels_per_pt: f32, // todo: Currently unused.
    ) -> RenderPass<'a> {
        let (x, y, eff_width, eff_height) =
            viewport_rect(ui_size, win_width, win_height, ui_settings, pixels_per_pt);

        let color_attachment = if let Some(msaa_texture) = &self.msaa_texture {
            // Use MSAA texture as render target, resolve to the swap chain texture
            wgpu::RenderPassColorAttachment {
                view: msaa_texture,
                depth_slice: None, // todo: Introduced in GPU27. Should we use it?
                resolve_target: Some(output_view), // Resolve the multisample texture
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                    store: StoreOp::Discard,
                },
            }
        } else {
            wgpu::RenderPassColorAttachment {
                view: output_view,
                depth_slice: None,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color {
                        r: self.scene.background_color.0 as f64,
                        g: self.scene.background_color.1 as f64,
                        b: self.scene.background_color.2 as f64,
                        a: 1.0,
                    }),
                    store: StoreOp::Store,
                },
            }
        };

        let mut rpass = encoder.begin_render_pass(&RenderPassDescriptor {
            label: Some("Render pass"),
            color_attachments: &[Some(color_attachment)],
            depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
                view: &self.depth_texture.view,
                depth_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(1.0),
                    store: StoreOp::Store,
                }),
                stencil_ops: None,
            }),
            timestamp_writes: None,
            occlusion_query_set: None,
        });

        rpass.set_viewport(x, y, eff_width, eff_height, 0., 1.);

        // Depth-aware halo prepass: render opaque instances inflated along normals, front-face
        // culled, writing only to the depth buffer. Background fragments near a foreground
        // silhouette then fail the depth test in the main render, producing a halo ring.
        if self.halo_expansion > 0.0 && self.instance_buf.size() > 0 {
            rpass.set_pipeline(&self.pipeline_halo);
            rpass.set_bind_group(0, &self.bind_group_cam_halo, &[]);
            rpass.set_bind_group(1, &self.bind_groups.lighting, &[]);
            rpass.set_vertex_buffer(0, self.vertex_buf.slice(..));
            rpass.set_vertex_buffer(1, self.instance_buf.slice(..));
            rpass.set_index_buffer(self.index_buf.slice(..), wgpu::IndexFormat::Uint32);

            let mut start_ind = 0u32;
            for (i, mesh) in self.scene.meshes.iter().enumerate() {
                let (vertex_start, instance_start, instance_count) = self.mesh_mappings[i];
                if instance_count == 0 {
                    start_ind += mesh.indices.len() as u32;
                    continue;
                }
                rpass.draw_indexed(
                    start_ind..start_ind + mesh.indices.len() as u32,
                    vertex_start,
                    instance_start..instance_start + instance_count,
                );
                start_ind += mesh.indices.len() as u32;
            }
        }

        // Make a render pass for opaque meshes, and transparent ones. We separate them to only
        // back-cull opaque ones.
        // We draw transparent meshes in two passes, for proper surface culling.
        for (inst_buf, pipeline, mappings) in [
            (&self.instance_buf, &self.pipeline_mesh, &self.mesh_mappings),
            // The order might matter here, i.e. running the back transparent pipeline before
            // the front transparent one.
            (
                &self.instance_buf_transparent,
                &self.pipeline_mesh_transparent_back,
                &self.mesh_mappings_transparent,
            ),
            (
                &self.instance_buf_transparent,
                &self.pipeline_mesh_transparent,
                &self.mesh_mappings_transparent,
            ),
        ]
        .into_iter()
        {
            if inst_buf.size() == 0 {
                continue;
            }

            rpass.set_pipeline(pipeline);
            rpass.set_bind_group(0, &self.bind_groups.cam, &[]);
            rpass.set_bind_group(1, &self.bind_groups.lighting, &[]);

            rpass.set_vertex_buffer(0, self.vertex_buf.slice(..));
            rpass.set_vertex_buffer(1, inst_buf.slice(..));
            rpass.set_index_buffer(self.index_buf.slice(..), wgpu::IndexFormat::Uint32);

            let mut start_ind = 0;
            for (i, mesh) in self.scene.meshes.iter().enumerate() {
                let (vertex_start_this_mesh, instance_start_this_mesh, instance_count_this_mesh) =
                    mappings[i];

                if instance_count_this_mesh == 0 {
                    start_ind += mesh.indices.len() as u32;
                    continue;
                }

                rpass.draw_indexed(
                    start_ind..start_ind + mesh.indices.len() as u32,
                    vertex_start_this_mesh,
                    instance_start_this_mesh..instance_start_this_mesh + instance_count_this_mesh,
                );

                start_ind += mesh.indices.len() as u32;
            }
        }

        // Draw gaussians.
        if !self.scene.gaussians.is_empty() {
            rpass.set_pipeline(&self.pipeline_gauss);

            rpass.set_bind_group(0, &self.bind_groups.cam_gauss, &[]);

            rpass.set_vertex_buffer(0, self.vertex_buf_quad.slice(..));
            rpass.set_vertex_buffer(1, self.instance_buf_gauss.slice(..)); // stride = 32 B

            rpass.draw(0..6, 0..self.scene.gaussians.len() as _); // 6 indices for the quad
        }

        // Apply the calculated viewport
        rpass.set_viewport(x, y, eff_width, eff_height, 0., 1.);

        rpass
    }

    /// The entry point to 3D and GUI rendering.
    /// Note: `resize_required`, the return, is to handle changes in GUI size.
    pub(crate) fn render<T>(
        &mut self,
        gui: &mut GuiState,
        surface_texture: SurfaceTexture,
        output_texture: &TextureView,
        device: &Device,
        queue: &Queue,
        dt: Duration,
        width: u32,
        height: u32,
        ui_settings: &mut UiSettings,
        gui_handler: impl FnMut(&mut T, &Context, &mut Scene) -> EngineUpdates,
        user_state: &mut T,
    ) -> bool {
        // Adjust camera inputs using the in-engine control scheme.
        // Note that camera settings adjusted by the application code are handled in
        // `update_camera`.

        if self.inputs_commanded.inputs_present() {
            let dt_secs = dt.as_secs() as f32 + dt.subsec_micros() as f32 / 1_000_000.;

            let cam_changed = match self.scene.input_settings.control_scheme {
                ControlScheme::FreeCamera => input::adjust_camera_free(
                    &mut self.scene.camera,
                    &mut self.inputs_commanded,
                    &self.scene.input_settings,
                    dt_secs,
                ),
                ControlScheme::Arc { center } => input::adjust_camera_arc(
                    &mut self.scene.camera,
                    &mut self.inputs_commanded,
                    &self.scene.input_settings,
                    center,
                    dt_secs,
                ),
                ControlScheme::None => false,
                ControlScheme::Fps => unimplemented!(),
            };

            if cam_changed {
                self.update_camera(queue);
            }

            // Reset the mouse inputs; keyboard inputs are reset by their release event.
            self.inputs_commanded.mouse_delta_x = 0.;
            self.inputs_commanded.mouse_delta_y = 0.;
        }

        // We create a CommandEncoder to create the actual commands to send to the
        // gpu. Most modern graphics frameworks expect commands to be stored in a command buffer
        // before being sent to the gpu. The encoder builds a command buffer that we can then
        // send to the gpu.
        let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor {
            label: Some("Render encoder"),
        });

        let mut updates_gui = Default::default();

        let (gui_full_output, tris, screen_descriptor, resize_required) = gui.render_gui_pre_rpass(
            self,
            user_state,
            device,
            gui_handler,
            &mut encoder,
            queue,
            width,
            height,
            &mut updates_gui,
        );

        // Draw text on the screen.
        draw_text_overlay(self, gui, ui_settings, width, height);

        // Note: If we process engine updates after setting up the render pass, we will not be
        // able to add meshes at runtime; code run from the `engine_updates.meshes` flag must be
        // done along with a mesh change prior to setting up the render pass, or else we will get
        // an error about an index being out of bounds.
        process_engine_updates(&updates_gui, self, device, queue);

        // Geometry prepass: render opaque geometry into the 1-sample depth texture used
        // by both contour lines and SSAO.
        let contours_active = self.depth_revealing > 0. || self.intersection_revealing > 0.;
        let ssao_active = self.ssao_strength > 0.;
        let prepass_active = contours_active || ssao_active;
        if prepass_active && self.instance_buf.size() > 0 {
            let mut pre = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Contour depth prepass"),
                color_attachments: &[],
                depth_stencil_attachment: Some(RenderPassDepthStencilAttachment {
                    view: &self.depth_texture_contour.view,
                    depth_ops: Some(wgpu::Operations {
                        load: wgpu::LoadOp::Clear(1.0),
                        store: StoreOp::Store,
                    }),
                    stencil_ops: None,
                }),
                timestamp_writes: None,
                occlusion_query_set: None,
            });
            pre.set_pipeline(&self.pipeline_contour_depth);
            pre.set_bind_group(0, &self.bind_groups.cam, &[]);
            pre.set_vertex_buffer(0, self.vertex_buf.slice(..));
            pre.set_vertex_buffer(1, self.instance_buf.slice(..));
            pre.set_index_buffer(self.index_buf.slice(..), wgpu::IndexFormat::Uint32);
            let mut start_ind = 0u32;
            for (i, mesh) in self.scene.meshes.iter().enumerate() {
                let (vertex_start, instance_start, instance_count) = self.mesh_mappings[i];
                if instance_count == 0 {
                    start_ind += mesh.indices.len() as u32;
                    continue;
                }
                pre.draw_indexed(
                    start_ind..start_ind + mesh.indices.len() as u32,
                    vertex_start,
                    instance_start..instance_start + instance_count,
                );
                start_ind += mesh.indices.len() as u32;
            }
            drop(pre);
        }

        let rpass = self.setup_render_pass(
            &mut encoder,
            output_texture,
            width,
            height,
            ui_settings, // Pass settings
            gui.size,    // Pass current size
            0.,          // pixels per point. A/R.
        );

        // Update aspect ratio based on the ACTUAL 3D viewport size,
        // not the window size.
        // We have to calculate the effective size locally here again, or return it
        // from setup_render_pass. Calculating it simply here:
        let mut viewport_w = width as f32;
        let mut viewport_h = height as f32;

        viewport_w -= gui.size.0;
        viewport_h -= gui.size.1;

        if viewport_w > 0.0 && viewport_h > 0.0 {
            self.scene.camera.aspect = viewport_w / viewport_h;
            self.scene.camera.update_proj_mat();
            self.update_camera(queue);
        }

        drop(rpass); // End the 3D render pass (MSAA resolve happens here).

        // Contour overlay: alpha-blend dark lines on top of the resolved scene.
        if contours_active {
            let mut overlay = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Contour overlay"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: output_texture,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load, // preserve the rendered scene
                        store: StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
            });
            overlay.set_pipeline(&self.pipeline_contour_overlay);
            overlay.set_bind_group(0, &self.bind_group_contour, &[]);
            overlay.draw(0..3, 0..1); // full-screen triangle
            drop(overlay);
        }

        // SSAO overlay: darken ambient-occluded areas via multiplicative blend.
        if ssao_active {
            self.update_ssao_uniforms(queue);
            let mut overlay = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("SSAO overlay"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: output_texture,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Load, // preserve the rendered scene
                        store: StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
            });
            overlay.set_pipeline(&self.pipeline_ssao);
            overlay.set_bind_group(0, &self.bind_group_ssao, &[]);
            overlay.draw(0..3, 0..1); // full-screen triangle
            drop(overlay);
        }

        // Egui pass – runs after all overlays so scene effects never paint over
        // the UI.  Always 1× MSAA so it never needs to be recreated when the
        // 3D MSAA level changes.
        {
            let mut egui_pass = encoder
                .begin_render_pass(&wgpu::RenderPassDescriptor {
                    label: Some("egui render pass"),
                    color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                        view: output_texture,
                        depth_slice: None,
                        resolve_target: None,
                        ops: wgpu::Operations {
                            load: wgpu::LoadOp::Load,
                            store: StoreOp::Store,
                        },
                    })],
                    depth_stencil_attachment: None,
                    timestamp_writes: None,
                    occlusion_query_set: None,
                })
                .forget_lifetime();
            gui.egui_renderer
                .render(&mut egui_pass, &tris, &screen_descriptor);
        }

        for x in &gui_full_output.textures_delta.free {
            gui.egui_renderer.free_texture(x)
        }

        queue.submit(Some(encoder.finish()));

        surface_texture.present();

        resize_required
    }
}

/// Create a render pipeline. Configurable by parameters to support multiple use cases. E.g., both
/// meshes and gaussians.
fn create_render_pipeline(
    device: &Device,
    layout: &wgpu::PipelineLayout,
    shader: wgpu::ShaderModule,
    config: &SurfaceConfiguration,
    sample_count: u32,
    vertex_buffers: &'static [VertexBufferLayout<'static>],
    depth_stencil: Option<DepthStencilState>,
    blend: Option<BlendState>,
    cull_mode: Option<Face>,
    label: &str,
) -> RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some(label),
        layout: Some(layout),

        vertex: VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: vertex_buffers,
        },
        fragment: Some(FragmentState {
            module: &shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            // This configures with alpha blending. (?)
            targets: &[Some(wgpu::ColorTargetState {
                format: config.format, // Ensure this is a format with alpha (e.g., `wgpu::TextureFormat::Rgba8Unorm`)
                blend,
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode,
            unclipped_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        },

        depth_stencil,
        multisample: wgpu::MultisampleState {
            count: sample_count, // Enable MSAA
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        // If the pipeline will be used with a multiview render pass, this
        // indicates how many array layers the attachments will have.
        multiview: None,
        cache: None,
    })
}

/// Depth-only pipeline (no fragment stage). Used for the halo prepass.
fn create_render_pipeline_depth_only(
    device: &Device,
    layout: &wgpu::PipelineLayout,
    shader: wgpu::ShaderModule,
    sample_count: u32,
    vertex_buffers: &'static [VertexBufferLayout<'static>],
    depth_stencil: DepthStencilState,
) -> RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("Halo depth-only pipeline"),
        layout: Some(layout),
        vertex: VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: vertex_buffers,
        },
        // Fragment stage declared to match the render pass color attachment format,
        // but write_mask is empty so nothing is actually written to color.
        fragment: Some(FragmentState {
            module: &shader,
            entry_point: Some("fs_main"),
            compilation_options: Default::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format: COLOR_FORMAT,
                blend: None,
                write_mask: wgpu::ColorWrites::empty(),
            })],
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            // Cull front faces so only back faces of the inflated mesh write depth,
            // which places those values *behind* the real surface at the same pixel.
            cull_mode: Some(Face::Front),
            unclipped_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        },
        depth_stencil: Some(depth_stencil),
        multisample: wgpu::MultisampleState {
            count: sample_count,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

/// Returns the 32-byte ContourUniforms buffer content matching shader_contour.wgsl.
pub(crate) fn contour_uniform_bytes(
    depth_threshold: f32,
    depth_revealing: f32,
    intersection_revealing: f32,
    near: f32,
    far: f32,
) -> [u8; 32] {
    let mut b = [0u8; 32];
    b[0..4].copy_from_slice(&depth_threshold.to_ne_bytes());
    b[4..8].copy_from_slice(&depth_revealing.to_ne_bytes());
    b[8..12].copy_from_slice(&intersection_revealing.to_ne_bytes());
    b[12..16].copy_from_slice(&near.to_ne_bytes());
    b[16..20].copy_from_slice(&far.to_ne_bytes());
    b
}

/// Depth-only prepass pipeline for the contour effect (1-sample, back-face cull, no color output).
fn create_contour_depth_pipeline(
    device: &Device,
    layout: &wgpu::PipelineLayout,
    shader: wgpu::ShaderModule,
    vertex_buffers: &'static [VertexBufferLayout<'static>],
) -> RenderPipeline {
    let depth_stencil = DepthStencilState {
        format: DEPTH_FORMAT,
        depth_write_enabled: true,
        depth_compare: wgpu::CompareFunction::Less,
        stencil: wgpu::StencilState::default(),
        bias: wgpu::DepthBiasState::default(),
    };
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("Contour depth prepass pipeline"),
        layout: Some(layout),
        vertex: VertexState {
            module: &shader,
            entry_point: Some("vs_main"),
            compilation_options: Default::default(),
            buffers: vertex_buffers,
        },
        fragment: None, // No color attachment in this pass → compatible.
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: Some(Face::Back),
            unclipped_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        },
        depth_stencil: Some(depth_stencil),
        multisample: wgpu::MultisampleState {
            count: 1, // Always 1-sample; the depth_texture_contour is 1-sample.
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

/// Full-screen alpha-blended pipeline for overlaying contour lines on the scene.
fn create_contour_overlay_pipeline(
    device: &Device,
    layout: &wgpu::PipelineLayout,
    shader: wgpu::ShaderModule,
    config: &SurfaceConfiguration,
) -> RenderPipeline {
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("Contour overlay pipeline"),
        layout: Some(layout),
        vertex: VertexState {
            module: &shader,
            entry_point: Some("vs_contour"),
            compilation_options: Default::default(),
            buffers: &[], // positions from vertex_index
        },
        fragment: Some(FragmentState {
            module: &shader,
            entry_point: Some("fs_contour"),
            compilation_options: Default::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format: config.format,
                blend: Some(BlendState::ALPHA_BLENDING),
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: None,
            unclipped_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        },
        depth_stencil: None, // No depth attachment in the overlay pass.
        multisample: wgpu::MultisampleState {
            count: 1,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

pub(crate) fn create_contour_bind_group(
    device: &Device,
    layout: &wgpu::BindGroupLayout,
    depth_view: &TextureView,
    uniform_buf: &Buffer,
) -> wgpu::BindGroup {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("Contour bind group"),
        layout,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::TextureView(depth_view),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: uniform_buf.as_entire_binding(),
            },
        ],
    })
}

// ── SSAO helpers ─────────────────────────────────────────────────────────────

/// Size of the SsaoUniforms struct as laid out in shader_ssao.wgsl (std140).
/// Layout: proj_view (64) + proj_view_inv (64) + cam_pos (16) + 8×f32 (32) = 176 bytes.
pub(crate) const SSAO_UNIFORM_SIZE: usize = 176;

/// Build the raw bytes for the SSAO uniform buffer.
pub(crate) fn ssao_uniform_bytes(
    proj_view: &Mat4,
    proj_view_inv: &Mat4,
    cam_pos: Vec3,
    near: f32,
    far: f32,
    radius: f32,
    bias: f32,
    strength: f32,
) -> [u8; SSAO_UNIFORM_SIZE] {
    let mut b = [0u8; SSAO_UNIFORM_SIZE];
    b[0..64].copy_from_slice(&proj_view.to_bytes());
    b[64..128].copy_from_slice(&proj_view_inv.to_bytes());
    // cam_pos as vec4 (w = 0)
    b[128..132].copy_from_slice(&cam_pos.x.to_ne_bytes());
    b[132..136].copy_from_slice(&cam_pos.y.to_ne_bytes());
    b[136..140].copy_from_slice(&cam_pos.z.to_ne_bytes());
    b[140..144].copy_from_slice(&0f32.to_ne_bytes());
    b[144..148].copy_from_slice(&near.to_ne_bytes());
    b[148..152].copy_from_slice(&far.to_ne_bytes());
    b[152..156].copy_from_slice(&radius.to_ne_bytes());
    b[156..160].copy_from_slice(&bias.to_ne_bytes());
    b[160..164].copy_from_slice(&strength.to_ne_bytes());
    // _pad0.._pad2 remain zero
    b
}

pub(crate) fn create_ssao_bind_group(
    device: &Device,
    layout: &wgpu::BindGroupLayout,
    depth_view: &TextureView,
    uniform_buf: &Buffer,
) -> wgpu::BindGroup {
    device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("SSAO bind group"),
        layout,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::TextureView(depth_view),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: uniform_buf.as_entire_binding(),
            },
        ],
    })
}

/// Full-screen alpha-blended (multiplicative) pipeline for the SSAO overlay.
fn create_ssao_pipeline(
    device: &Device,
    layout: &wgpu::PipelineLayout,
    shader: wgpu::ShaderModule,
    config: &SurfaceConfiguration,
) -> RenderPipeline {
    use wgpu::{BlendComponent, BlendFactor, BlendOperation};
    // Multiplicative blend: scene_color * ao_factor.
    // result = src * Zero + dst * SrcColor = dst * ao
    let multiply_blend = BlendState {
        color: BlendComponent {
            src_factor: BlendFactor::Zero,
            dst_factor: BlendFactor::Src,
            operation: BlendOperation::Add,
        },
        alpha: BlendComponent {
            src_factor: BlendFactor::Zero,
            dst_factor: BlendFactor::One,
            operation: BlendOperation::Add,
        },
    };
    device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
        label: Some("SSAO overlay pipeline"),
        layout: Some(layout),
        vertex: VertexState {
            module: &shader,
            entry_point: Some("vs_ssao"),
            compilation_options: Default::default(),
            buffers: &[],
        },
        fragment: Some(FragmentState {
            module: &shader,
            entry_point: Some("fs_ssao"),
            compilation_options: Default::default(),
            targets: &[Some(wgpu::ColorTargetState {
                format: config.format,
                blend: Some(multiply_blend),
                write_mask: wgpu::ColorWrites::ALL,
            })],
        }),
        primitive: wgpu::PrimitiveState {
            topology: wgpu::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            front_face: wgpu::FrontFace::Ccw,
            cull_mode: None,
            unclipped_depth: false,
            polygon_mode: wgpu::PolygonMode::Fill,
            conservative: false,
        },
        depth_stencil: None,
        multisample: wgpu::MultisampleState {
            count: 1,
            mask: !0,
            alpha_to_coverage_enabled: false,
        },
        multiview: None,
        cache: None,
    })
}

// ── End SSAO helpers ──────────────────────────────────────────────────────────

pub(crate) struct BindGroupData {
    pub layout_cam: BindGroupLayout,
    pub cam: BindGroup,
    pub layout_cam_gauss: BindGroupLayout,
    pub cam_gauss: BindGroup,
    pub layout_lighting: BindGroupLayout,
    pub lighting: BindGroup,
    /// We use this for GUI.
    pub _layout_texture: BindGroupLayout,
    // pub texture: BindGroup,
}

fn create_bindgroups(
    device: &Device,
    cam_buf: &Buffer,
    // cam_buf_sep: &Buffer,
    cam_basis_buf: &Buffer,
    lighting_buf: &Buffer,
) -> BindGroupData {
    let cam_entry = wgpu::BindGroupLayoutEntry {
        binding: 0,
        visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
        ty: BindingType::Buffer {
            ty: BufferBindingType::Uniform,
            // The dynamic field indicates whether this buffer will change size or
            // not. This is useful if we want to store an array of things in our uniforms.
            has_dynamic_offset: false,
            min_binding_size: wgpu::BufferSize::new(CAMERA_SIZE as _),
        },
        count: None,
    };

    // We only need vertex, not fragment info in the camera uniform.
    let layout_cam = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        entries: std::slice::from_ref(&cam_entry),
        label: Some("Camera bind group layout"),
    });

    let cam = device.create_bind_group(&wgpu::BindGroupDescriptor {
        layout: &layout_cam,
        entries: &[wgpu::BindGroupEntry {
            binding: 0,
            resource: cam_buf.as_entire_binding(),
        }],
        label: Some("Camera bind group"),
    });

    let layout_cam_gauss = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        entries: &[
            cam_entry,
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
                ty: BindingType::Buffer {
                    ty: BufferBindingType::Uniform,
                    // The dynamic field indicates whether this buffer will change size or
                    // not. This is useful if we want to store an array of things in our uniforms.
                    has_dynamic_offset: false,
                    min_binding_size: wgpu::BufferSize::new(CAM_BASIS_SIZE as _),
                },
                count: None,
            },
        ],
        label: Some("Camera gaussian bind group layout"),
    });

    let cam_gauss = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("Gaussian camera bind group"),
        layout: &layout_cam_gauss,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                // resource: cam_buf_sep.as_entire_binding(),
                resource: cam_buf.as_entire_binding(),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: cam_basis_buf.as_entire_binding(),
            },
        ],
    });

    let layout_lighting = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        entries: &[wgpu::BindGroupLayoutEntry {
            binding: 0,
            visibility: ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Storage { read_only: true }, // todo read-only?
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }],
        label: Some("Lighting bind group layout"),
    });

    let lighting = device.create_bind_group(&wgpu::BindGroupDescriptor {
        layout: &layout_lighting,
        entries: &[wgpu::BindGroupEntry {
            binding: 0,
            resource: lighting_buf.as_entire_binding(),
        }],
        label: Some("Lighting bind group"),
    });

    // todo: Don't create these (diffuse tex view, sampler every time. Pass as args.
    // We don't need to configure the texture view much, so let's
    // let wgpu define it.
    // let diffuse_bytes = include_bytes!("happy-tree.png");
    // let diffuse_bytes = [];
    // let diffuse_texture = wgpu::texture::Texture::from_bytes(&device, &queue, diffuse_bytes, "happy-tree.png").unwrap();
    //
    // let diffuse_texture_view = diffuse_texture.create_view(&wgpu::TextureViewDescriptor::default());
    // let diffuse_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
    //     address_mode_u: wgpu::AddressMode::ClampToEdge,
    //     address_mode_v: wgpu::AddressMode::ClampToEdge,
    //     address_mode_w: wgpu::AddressMode::ClampToEdge,
    //     mag_filter: wgpu::FilterMode::Linear,
    //     min_filter: wgpu::FilterMode::Nearest,
    //     mipmap_filter: wgpu::FilterMode::Nearest,
    //     ..Default::default()
    // });

    let layout_texture = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("egui_texture_bind_group_layout"),
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                ty: BindingType::Texture {
                    multisampled: false,
                    view_dimension: wgpu::TextureViewDimension::D2,
                    sample_type: wgpu::TextureSampleType::Float { filterable: true },
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                // This should match the filterable field of the
                // corresponding Texture entry above.
                ty: BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                count: None,
            },
        ],
    });

    // let texture = device.create_bind_group(
    //     &wgpu::BindGroupDescriptor {
    //         layout: &layout_texture,
    //         entries: &[
    //             wgpu::BindGroupEntry {
    //                 binding: 0,
    //                 resource: wgpu::BindingResource::TextureView(&diffuse_texture_view),
    //                 // resource: wgpu::BindingResource::TextureView(&[]), // todo?
    //             },
    //             wgpu::BindGroupEntry {
    //                 binding: 1,
    //                 resource: wgpu::BindingResource::Sampler(&diffuse_sampler),
    //             }
    //         ],
    //         label: Some("Texture bind group"),
    //     });

    BindGroupData {
        layout_cam,
        cam,
        layout_cam_gauss,
        cam_gauss,
        layout_lighting,
        lighting,
        _layout_texture: layout_texture,
        // texture
    }
}

fn setup_instance_buf(device: &Device, instances: &[Instance], name: &str) -> Buffer {
    let mut instance_data = Vec::with_capacity(instances.len() * INSTANCE_SIZE);

    for instance in instances {
        for byte in instance.to_bytes() {
            instance_data.push(byte);
        }
    }

    // We can't update using a queue due to buffer size mismatches.
    device.create_buffer_init(&BufferInitDescriptor {
        label: Some(name),
        contents: &instance_data,
        // usage: BufferUsages::VERTEX,
        // COPY_DST allows us to copy updates into an existing buffer.
        usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
    })
}

// todo: DRY due simply to the instance type being different.
fn setup_instance_buf_gauss(device: &Device, instances: &[GaussianInstance], name: &str) -> Buffer {
    let mut instance_data = Vec::with_capacity(instances.len() * INSTANCE_SIZE);

    for instance in instances {
        for byte in instance.to_bytes() {
            instance_data.push(byte);
        }
    }

    // We can't update using a queue due to buffer size mismatches.
    device.create_buffer_init(&BufferInitDescriptor {
        label: Some(name),
        contents: &instance_data,
        // usage: BufferUsages::VERTEX,
        usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
    })
}