runmat-plot 0.4.0

GPU-accelerated and static plotting for RunMat with WGPU and Plotters
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
//! WGPU-based rendering backend for high-performance plotting
//!
//! This module provides GPU-accelerated rendering using WGPU, supporting
//! both desktop and web targets for maximum compatibility.

use bytemuck::{Pod, Zeroable};
use glam::{Mat4, Vec3, Vec4};
use std::sync::Arc;
use wgpu::util::DeviceExt;

use crate::core::DepthMode;
use crate::{core::scene::GpuVertexBuffer, gpu::shaders};

/// Uniforms for the procedural 3D grid plane.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct GridUniforms {
    pub major_step: f32,
    pub minor_step: f32,
    pub fade_start: f32,
    pub fade_end: f32,
    pub camera_pos: [f32; 3],
    pub _pad0: f32,
    pub target_pos: [f32; 3],
    pub _pad1: f32,
    pub major_color: [f32; 4],
    pub minor_color: [f32; 4],
}

impl Default for GridUniforms {
    fn default() -> Self {
        Self {
            major_step: 1.0,
            minor_step: 0.1,
            fade_start: 10.0,
            fade_end: 15.0,
            camera_pos: [0.0, 0.0, 0.0],
            _pad0: 0.0,
            target_pos: [0.0, 0.0, 0.0],
            _pad1: 0.0,
            major_color: [0.90, 0.92, 0.96, 0.30],
            minor_color: [0.82, 0.84, 0.88, 0.18],
        }
    }
}

/// Vertex data for rendering points, lines, and triangles
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Vertex {
    pub position: [f32; 3],
    pub color: [f32; 4],
    pub normal: [f32; 3],
    pub tex_coords: [f32; 2],
}

impl Vertex {
    pub fn new(position: Vec3, color: Vec4) -> Self {
        Self {
            position: position.to_array(),
            color: color.to_array(),
            normal: [0.0, 0.0, 1.0], // Default normal
            tex_coords: [0.0, 0.0],  // Default UV
        }
    }

    pub fn desc() -> wgpu::VertexBufferLayout<'static> {
        let stride = std::mem::size_of::<Vertex>() as wgpu::BufferAddress;
        log::trace!(
            target: "runmat_plot",
            "vertex layout: size={}, stride={}",
            std::mem::size_of::<Vertex>(),
            stride
        );
        wgpu::VertexBufferLayout {
            array_stride: stride,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &[
                // Position
                wgpu::VertexAttribute {
                    offset: 0,
                    shader_location: 0,
                    format: wgpu::VertexFormat::Float32x3,
                },
                // Color
                wgpu::VertexAttribute {
                    offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
                    shader_location: 1,
                    format: wgpu::VertexFormat::Float32x4,
                },
                // Normal
                wgpu::VertexAttribute {
                    offset: std::mem::size_of::<[f32; 7]>() as wgpu::BufferAddress,
                    shader_location: 2,
                    format: wgpu::VertexFormat::Float32x3,
                },
                // Texture coordinates
                wgpu::VertexAttribute {
                    offset: std::mem::size_of::<[f32; 10]>() as wgpu::BufferAddress,
                    shader_location: 3,
                    format: wgpu::VertexFormat::Float32x2,
                },
            ],
        }
    }
}

/// Uniform buffer for camera and transformation matrices
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct Uniforms {
    pub view_proj: [[f32; 4]; 4],
    pub model: [[f32; 4]; 4],
    pub normal_matrix: [[f32; 4]; 3], // Use 4x3 for proper alignment instead of 3x3
}

/// Optimized uniform buffer for direct coordinate transformation rendering
/// Enables precise viewport-constrained data visualization
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct DirectUniforms {
    pub data_min: [f32; 2],     // (x_min, y_min) in data space
    pub data_max: [f32; 2],     // (x_max, y_max) in data space
    pub viewport_min: [f32; 2], // NDC coordinates of viewport bottom-left
    pub viewport_max: [f32; 2], // NDC coordinates of viewport top-right
    pub viewport_px: [f32; 2],  // viewport size in pixels (width, height)
}

/// Style uniforms for direct point rendering (scatter markers)
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable)]
pub struct PointStyleUniforms {
    pub face_color: [f32; 4],
    pub edge_color: [f32; 4],
    pub edge_thickness_px: f32,
    pub marker_shape: u32,
    pub _pad: [f32; 2],
}

impl Default for Uniforms {
    fn default() -> Self {
        Self::new()
    }
}

impl Uniforms {
    pub fn new() -> Self {
        Self {
            view_proj: Mat4::IDENTITY.to_cols_array_2d(),
            model: Mat4::IDENTITY.to_cols_array_2d(),
            normal_matrix: [
                [1.0, 0.0, 0.0, 0.0],
                [0.0, 1.0, 0.0, 0.0],
                [0.0, 0.0, 1.0, 0.0],
            ],
        }
    }

    pub fn update_view_proj(&mut self, view_proj: Mat4) {
        self.view_proj = view_proj.to_cols_array_2d();
    }

    pub fn update_model(&mut self, model: Mat4) {
        self.model = model.to_cols_array_2d();
        // Update normal matrix (upper 3x3 of inverse transpose) with proper alignment
        let normal_mat = model.inverse().transpose();
        self.normal_matrix = [
            [
                normal_mat.x_axis.x,
                normal_mat.x_axis.y,
                normal_mat.x_axis.z,
                0.0,
            ],
            [
                normal_mat.y_axis.x,
                normal_mat.y_axis.y,
                normal_mat.y_axis.z,
                0.0,
            ],
            [
                normal_mat.z_axis.x,
                normal_mat.z_axis.y,
                normal_mat.z_axis.z,
                0.0,
            ],
        ];
    }
}

impl DirectUniforms {
    pub fn new(
        data_min: [f32; 2],
        data_max: [f32; 2],
        viewport_min: [f32; 2],
        viewport_max: [f32; 2],
        viewport_px: [f32; 2],
    ) -> Self {
        Self {
            data_min,
            data_max,
            viewport_min,
            viewport_max,
            viewport_px,
        }
    }
}

pub fn marker_shape_code(style: crate::plots::scatter::MarkerStyle) -> u32 {
    match style {
        crate::plots::scatter::MarkerStyle::Circle => 0,
        crate::plots::scatter::MarkerStyle::Square => 1,
        crate::plots::scatter::MarkerStyle::Triangle => 2,
        crate::plots::scatter::MarkerStyle::Diamond => 3,
        crate::plots::scatter::MarkerStyle::Plus => 4,
        crate::plots::scatter::MarkerStyle::Cross => 5,
        crate::plots::scatter::MarkerStyle::Star => 6,
        crate::plots::scatter::MarkerStyle::Hexagon => 7,
    }
}

/// Rendering pipeline types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PipelineType {
    Points,
    Lines,
    Triangles,
    Scatter3,
    Textured,
}

/// High-performance WGPU renderer for interactive plotting
pub struct WgpuRenderer {
    pub device: Arc<wgpu::Device>,
    pub queue: Arc<wgpu::Queue>,
    pub surface_config: wgpu::SurfaceConfiguration,

    // Global MSAA sample count for pipelines/attachments
    pub msaa_sample_count: u32,

    // Rendering pipelines (traditional camera-based)
    point_pipeline: Option<wgpu::RenderPipeline>,
    line_pipeline: Option<wgpu::RenderPipeline>,
    triangle_pipeline: Option<wgpu::RenderPipeline>,

    // Direct rendering pipelines (optimized coordinate transformation)
    pub direct_line_pipeline: Option<wgpu::RenderPipeline>,
    pub direct_triangle_pipeline: Option<wgpu::RenderPipeline>,
    pub direct_point_pipeline: Option<wgpu::RenderPipeline>,
    image_pipeline: Option<wgpu::RenderPipeline>,
    image_bind_group_layout: wgpu::BindGroupLayout,
    image_sampler: wgpu::Sampler,
    point_style_bind_group_layout: wgpu::BindGroupLayout,

    // Grid helper uniforms/pipeline (3D only)
    grid_uniform_buffer: wgpu::Buffer,
    pub grid_uniform_bind_group: wgpu::BindGroup,
    grid_uniform_bind_group_layout: wgpu::BindGroupLayout,
    axes_grid_uniform_buffers: Vec<wgpu::Buffer>,
    axes_grid_uniform_bind_groups: Vec<wgpu::BindGroup>,
    grid_plane_pipeline: Option<wgpu::RenderPipeline>,

    // Uniform resources (traditional)
    uniform_buffer: wgpu::Buffer,
    uniform_bind_group: wgpu::BindGroup,
    uniform_bind_group_layout: wgpu::BindGroupLayout,
    axes_uniform_buffers: Vec<wgpu::Buffer>,
    axes_uniform_bind_groups: Vec<wgpu::BindGroup>,

    // Direct uniform resources (optimized coordinate transformation)
    direct_uniform_buffer: wgpu::Buffer,
    pub direct_uniform_bind_group: wgpu::BindGroup,
    direct_uniform_bind_group_layout: wgpu::BindGroupLayout,
    axes_direct_uniform_buffers: Vec<wgpu::Buffer>,
    axes_direct_uniform_bind_groups: Vec<wgpu::BindGroup>,

    // Current uniforms
    uniforms: Uniforms,
    direct_uniforms: DirectUniforms,

    // Depth resources (used by camera-based 3D rendering paths)
    depth_texture: Option<wgpu::Texture>,
    depth_view: Option<Arc<wgpu::TextureView>>,
    depth_extent: (u32, u32, u32), // (w, h, sample_count)

    // MSAA color resources for resolving into single-sampled targets.
    msaa_color_texture: Option<wgpu::Texture>,
    msaa_color_view: Option<Arc<wgpu::TextureView>>,
    msaa_color_extent: (u32, u32, u32), // (w, h, sample_count)

    /// Depth mapping mode for camera-based 3D pipelines.
    pub depth_mode: DepthMode,
}

impl WgpuRenderer {
    fn create_uniform_bind_group_for_buffer(
        &self,
        buffer: &wgpu::Buffer,
        label: &str,
    ) -> wgpu::BindGroup {
        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &self.uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: buffer.as_entire_binding(),
            }],
            label: Some(label),
        })
    }

    fn create_direct_uniform_bind_group_for_buffer(
        &self,
        buffer: &wgpu::Buffer,
        label: &str,
    ) -> wgpu::BindGroup {
        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &self.direct_uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: buffer.as_entire_binding(),
            }],
            label: Some(label),
        })
    }

    fn create_grid_uniform_bind_group_for_buffer(
        &self,
        buffer: &wgpu::Buffer,
        label: &str,
    ) -> wgpu::BindGroup {
        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some(label),
            layout: &self.grid_uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: buffer.as_entire_binding(),
            }],
        })
    }

    pub fn ensure_axes_uniform_capacity(&mut self, axes_count: usize) {
        while self.axes_uniform_buffers.len() < axes_count {
            let idx = self.axes_uniform_buffers.len();
            let buffer = self
                .device
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some(&format!("Axes Uniform Buffer {idx}")),
                    contents: bytemuck::cast_slice(&[Uniforms::new()]),
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                });
            let bind_group = self.create_uniform_bind_group_for_buffer(
                &buffer,
                &format!("axes_uniform_bind_group_{idx}"),
            );
            self.axes_uniform_buffers.push(buffer);
            self.axes_uniform_bind_groups.push(bind_group);
        }
        while self.axes_direct_uniform_buffers.len() < axes_count {
            let idx = self.axes_direct_uniform_buffers.len();
            let buffer = self
                .device
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some(&format!("Axes Direct Uniform Buffer {idx}")),
                    contents: bytemuck::cast_slice(&[DirectUniforms::new(
                        [0.0, 0.0],
                        [1.0, 1.0],
                        [-1.0, -1.0],
                        [1.0, 1.0],
                        [1.0, 1.0],
                    )]),
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                });
            let bind_group = self.create_direct_uniform_bind_group_for_buffer(
                &buffer,
                &format!("axes_direct_uniform_bind_group_{idx}"),
            );
            self.axes_direct_uniform_buffers.push(buffer);
            self.axes_direct_uniform_bind_groups.push(bind_group);
        }
        while self.axes_grid_uniform_buffers.len() < axes_count {
            let idx = self.axes_grid_uniform_buffers.len();
            let buffer = self
                .device
                .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                    label: Some(&format!("Axes Grid Uniform Buffer {idx}")),
                    contents: bytemuck::cast_slice(&[GridUniforms::default()]),
                    usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                });
            let bind_group = self.create_grid_uniform_bind_group_for_buffer(
                &buffer,
                &format!("axes_grid_uniform_bind_group_{idx}"),
            );
            self.axes_grid_uniform_buffers.push(buffer);
            self.axes_grid_uniform_bind_groups.push(bind_group);
        }
    }

    /// Create a new WGPU renderer
    pub async fn new(
        device: Arc<wgpu::Device>,
        queue: Arc<wgpu::Queue>,
        surface_config: wgpu::SurfaceConfiguration,
    ) -> Self {
        // Create uniform buffer
        let uniforms = Uniforms::new();
        let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Uniform Buffer"),
            contents: bytemuck::cast_slice(&[uniforms]),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        });

        // Create bind group layout for uniforms
        let uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
                label: Some("uniform_bind_group_layout"),
            });

        // Create bind group
        let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
            label: Some("uniform_bind_group"),
        });

        // Create direct rendering uniform buffer
        let direct_uniforms = DirectUniforms::new(
            [0.0, 0.0],   // data_min
            [1.0, 1.0],   // data_max
            [-1.0, -1.0], // viewport_min (full NDC)
            [1.0, 1.0],   // viewport_max (full NDC)
            [1.0, 1.0],   // viewport_px
        );
        let direct_uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Direct Uniform Buffer"),
            contents: bytemuck::cast_slice(&[direct_uniforms]),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        });

        // Create direct bind group layout for uniforms
        let direct_uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
                label: Some("direct_uniform_bind_group_layout"),
            });

        // Create direct bind group
        let direct_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            layout: &direct_uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: direct_uniform_buffer.as_entire_binding(),
            }],
            label: Some("direct_uniform_bind_group"),
        });

        let image_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Image Bind Group Layout"),
                entries: &[
                    // sampler
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                        count: None,
                    },
                    // texture view
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::FRAGMENT,
                        ty: wgpu::BindingType::Texture {
                            multisampled: false,
                            view_dimension: wgpu::TextureViewDimension::D2,
                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        },
                        count: None,
                    },
                ],
            });

        let image_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("Image Sampler"),
            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::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        // Point style bind group layout (face/edge colors, thickness, shape)
        let point_style_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Point Style Bind Group Layout"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT | wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });

        // Grid uniforms (3D helper plane)
        let grid_uniforms = GridUniforms::default();
        let grid_uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Grid Uniform Buffer"),
            contents: bytemuck::cast_slice(&[grid_uniforms]),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        });
        let grid_uniform_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
                label: Some("grid_uniform_bind_group_layout"),
            });
        let grid_uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("grid_uniform_bind_group"),
            layout: &grid_uniform_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: grid_uniform_buffer.as_entire_binding(),
            }],
        });

        Self {
            device,
            queue,
            surface_config,
            msaa_sample_count: 1,
            point_pipeline: None,
            line_pipeline: None,
            triangle_pipeline: None,
            direct_line_pipeline: None,
            direct_triangle_pipeline: None,
            direct_point_pipeline: None,
            image_pipeline: None,
            image_bind_group_layout,
            image_sampler,
            point_style_bind_group_layout,
            grid_uniform_buffer,
            grid_uniform_bind_group,
            grid_uniform_bind_group_layout,
            axes_grid_uniform_buffers: Vec::new(),
            axes_grid_uniform_bind_groups: Vec::new(),
            grid_plane_pipeline: None,
            uniform_buffer,
            uniform_bind_group,
            uniform_bind_group_layout,
            axes_uniform_buffers: Vec::new(),
            axes_uniform_bind_groups: Vec::new(),
            direct_uniform_buffer,
            direct_uniform_bind_group,
            direct_uniform_bind_group_layout,
            axes_direct_uniform_buffers: Vec::new(),
            axes_direct_uniform_bind_groups: Vec::new(),
            uniforms,
            direct_uniforms,
            depth_texture: None,
            depth_view: None,
            depth_extent: (0, 0, 0),
            msaa_color_texture: None,
            msaa_color_view: None,
            msaa_color_extent: (0, 0, 0),
            depth_mode: DepthMode::default(),
        }
    }

    pub fn update_grid_uniforms(&mut self, uniforms: GridUniforms) {
        self.queue.write_buffer(
            &self.grid_uniform_buffer,
            0,
            bytemuck::cast_slice(&[uniforms]),
        );
        self.ensure_axes_uniform_capacity(1);
        self.queue.write_buffer(
            &self.axes_grid_uniform_buffers[0],
            0,
            bytemuck::cast_slice(&[uniforms]),
        );
    }

    pub fn update_grid_uniforms_for_axes(&mut self, axes_index: usize, uniforms: GridUniforms) {
        self.ensure_axes_uniform_capacity(axes_index + 1);
        self.queue.write_buffer(
            &self.axes_grid_uniform_buffers[axes_index],
            0,
            bytemuck::cast_slice(&[uniforms]),
        );
    }

    pub fn get_grid_uniform_bind_group_for_axes(&self, axes_index: usize) -> &wgpu::BindGroup {
        self.axes_grid_uniform_bind_groups
            .get(axes_index)
            .unwrap_or(&self.grid_uniform_bind_group)
    }

    pub fn set_depth_mode(&mut self, mode: DepthMode) {
        if self.depth_mode != mode {
            self.depth_mode = mode;
            // Pipelines depend on depth compare; rebuild.
            self.point_pipeline = None;
            self.line_pipeline = None;
            self.triangle_pipeline = None;
            self.direct_line_pipeline = None;
            self.direct_triangle_pipeline = None;
            self.direct_point_pipeline = None;
            self.image_pipeline = None;
            self.grid_plane_pipeline = None;
        }
    }

    /// Ensure MSAA state matches requested count. Rebuild pipelines if changed.
    pub fn ensure_msaa(&mut self, requested_count: u32) {
        let clamped = match requested_count {
            0 => 1,
            1 => 1,
            2 => 2,
            4 => 4,
            8 => 8,
            16 => 8, // clamp to 8 for portability
            _ => 4,  // default reasonable MSAA
        };
        if self.msaa_sample_count != clamped {
            self.msaa_sample_count = clamped;
            // Drop pipelines so they are recreated with new MSAA count
            self.point_pipeline = None;
            self.line_pipeline = None;
            self.triangle_pipeline = None;
            self.direct_line_pipeline = None;
            self.direct_triangle_pipeline = None;
            self.direct_point_pipeline = None;
            self.image_pipeline = None;
            self.grid_plane_pipeline = None;
            // Depth attachment must match sample count.
            self.depth_texture = None;
            self.depth_view = None;
            self.depth_extent = (0, 0, 0);
            self.msaa_color_texture = None;
            self.msaa_color_view = None;
            self.msaa_color_extent = (0, 0, 0);
        }
    }

    fn depth_format() -> wgpu::TextureFormat {
        // Prefer a higher-precision depth buffer on native; keep a web-friendly format on wasm.
        #[cfg(target_arch = "wasm32")]
        {
            wgpu::TextureFormat::Depth24Plus
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            wgpu::TextureFormat::Depth32Float
        }
    }

    fn depth_compare(&self) -> wgpu::CompareFunction {
        match self.depth_mode {
            DepthMode::Standard => wgpu::CompareFunction::LessEqual,
            DepthMode::ReversedZ => wgpu::CompareFunction::GreaterEqual,
        }
    }

    pub fn ensure_depth_view(&mut self) -> Arc<wgpu::TextureView> {
        let width = self.surface_config.width.max(1);
        let height = self.surface_config.height.max(1);
        let samples = self.msaa_sample_count.max(1);
        if self.depth_view.is_none() || self.depth_extent != (width, height, samples) {
            let texture = self.device.create_texture(&wgpu::TextureDescriptor {
                label: Some("runmat_depth_texture"),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: samples,
                dimension: wgpu::TextureDimension::D2,
                format: Self::depth_format(),
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.depth_texture = Some(texture);
            self.depth_view = Some(Arc::new(view));
            self.depth_extent = (width, height, samples);
        }
        self.depth_view
            .as_ref()
            .cloned()
            .expect("depth view missing")
    }

    pub fn ensure_msaa_color_view(&mut self) -> Arc<wgpu::TextureView> {
        let width = self.surface_config.width.max(1);
        let height = self.surface_config.height.max(1);
        let samples = self.msaa_sample_count.max(1);
        if self.msaa_color_view.is_none() || self.msaa_color_extent != (width, height, samples) {
            let texture = self.device.create_texture(&wgpu::TextureDescriptor {
                label: Some("runmat_msaa_color_plot"),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: samples,
                dimension: wgpu::TextureDimension::D2,
                format: self.surface_config.format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.msaa_color_texture = Some(texture);
            self.msaa_color_view = Some(Arc::new(view));
            self.msaa_color_extent = (width, height, samples);
        }
        self.msaa_color_view
            .as_ref()
            .cloned()
            .expect("msaa color view missing")
    }

    /// Create a GPU texture and bind group for an RGBA8 image
    pub fn create_image_texture_and_bind_group(
        &self,
        width: u32,
        height: u32,
        data: &[u8],
    ) -> (wgpu::Texture, wgpu::TextureView, wgpu::BindGroup) {
        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Image Texture"),
            size: wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8UnormSrgb,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        // Upload data
        self.queue.write_texture(
            wgpu::ImageCopyTexture {
                texture: &texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            data,
            wgpu::ImageDataLayout {
                offset: 0,
                bytes_per_row: Some(4 * width),
                rows_per_image: Some(height),
            },
            wgpu::Extent3d {
                width,
                height,
                depth_or_array_layers: 1,
            },
        );
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Image Bind Group"),
            layout: &self.image_bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::Sampler(&self.image_sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&texture_view),
                },
            ],
        });
        (texture, texture_view, bind_group)
    }

    /// Create a vertex buffer from vertex data
    pub fn create_vertex_buffer(&self, vertices: &[Vertex]) -> wgpu::Buffer {
        self.device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Vertex Buffer"),
                contents: bytemuck::cast_slice(vertices),
                usage: wgpu::BufferUsages::VERTEX,
            })
    }

    /// Choose the most efficient vertex buffer source for the provided data.
    pub fn vertex_buffer_from_sources(
        &self,
        gpu: Option<&GpuVertexBuffer>,
        cpu_vertices: &[Vertex],
    ) -> Option<Arc<wgpu::Buffer>> {
        if let Some(buffer) = gpu {
            Some(buffer.buffer.clone())
        } else if !cpu_vertices.is_empty() {
            Some(Arc::new(self.create_vertex_buffer(cpu_vertices)))
        } else {
            None
        }
    }

    /// Create a vertex buffer for direct points by expanding each point to a quad.
    /// This reuses Vertex but encodes corner index via tex_coords and marker size in normal.z
    pub fn create_direct_point_vertices(&self, points: &[Vertex], size_px: f32) -> Vec<Vertex> {
        let corners: [[f32; 2]; 6] = [
            [-1.0, -1.0],
            [1.0, -1.0],
            [1.0, 1.0],
            [-1.0, -1.0],
            [1.0, 1.0],
            [-1.0, 1.0],
        ];
        let mut out = Vec::with_capacity(points.len() * 6);
        for p in points {
            for c in corners {
                let mut v = *p;
                v.tex_coords = c; // tells shader which corner
                let sz = if size_px > 0.0 { size_px } else { p.normal[2] };
                v.normal = [p.normal[0], p.normal[1], sz];
                out.push(v);
            }
        }
        out
    }

    /// Create an index buffer from index data
    pub fn create_index_buffer(&self, indices: &[u32]) -> wgpu::Buffer {
        self.device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Index Buffer"),
                contents: bytemuck::cast_slice(indices),
                usage: wgpu::BufferUsages::INDEX,
            })
    }

    /// Update uniform buffer with new matrices
    pub fn update_uniforms(&mut self, view_proj: Mat4, model: Mat4) {
        self.uniforms.update_view_proj(view_proj);
        self.uniforms.update_model(model);

        self.queue.write_buffer(
            &self.uniform_buffer,
            0,
            bytemuck::cast_slice(&[self.uniforms]),
        );
        self.ensure_axes_uniform_capacity(1);
        self.queue.write_buffer(
            &self.axes_uniform_buffers[0],
            0,
            bytemuck::cast_slice(&[self.uniforms]),
        );
    }

    pub fn update_uniforms_for_axes(&mut self, axes_index: usize, view_proj: Mat4, model: Mat4) {
        self.ensure_axes_uniform_capacity(axes_index + 1);
        let mut uniforms = Uniforms::new();
        uniforms.update_view_proj(view_proj);
        uniforms.update_model(model);
        self.queue.write_buffer(
            &self.axes_uniform_buffers[axes_index],
            0,
            bytemuck::cast_slice(&[uniforms]),
        );
    }

    /// Get the uniform bind group for rendering
    pub fn get_uniform_bind_group(&self) -> &wgpu::BindGroup {
        &self.uniform_bind_group
    }

    pub fn get_uniform_bind_group_for_axes(&self, axes_index: usize) -> &wgpu::BindGroup {
        self.axes_uniform_bind_groups
            .get(axes_index)
            .unwrap_or(&self.uniform_bind_group)
    }

    /// Ensure pipeline exists for the specified type
    pub fn ensure_pipeline(&mut self, pipeline_type: PipelineType) {
        match pipeline_type {
            PipelineType::Points => {
                if self.point_pipeline.is_none() {
                    self.point_pipeline = Some(self.create_point_pipeline());
                }
            }
            PipelineType::Lines => {
                if self.line_pipeline.is_none() {
                    self.line_pipeline = Some(self.create_line_pipeline());
                }
            }
            PipelineType::Triangles => {
                if self.triangle_pipeline.is_none() {
                    self.triangle_pipeline = Some(self.create_triangle_pipeline());
                }
            }
            PipelineType::Scatter3 => {
                // For now, use points pipeline - will optimize later
                self.ensure_pipeline(PipelineType::Points);
            }
            PipelineType::Textured => {
                if self.image_pipeline.is_none() {
                    self.image_pipeline = Some(self.create_image_pipeline());
                }
            }
        }
    }

    /// Get a pipeline reference (pipeline must already exist)
    pub fn get_pipeline(&self, pipeline_type: PipelineType) -> &wgpu::RenderPipeline {
        match pipeline_type {
            PipelineType::Points => self.point_pipeline.as_ref().unwrap(),
            PipelineType::Lines => self.line_pipeline.as_ref().unwrap(),
            PipelineType::Triangles => self.triangle_pipeline.as_ref().unwrap(),
            PipelineType::Scatter3 => self.get_pipeline(PipelineType::Points),
            PipelineType::Textured => self.image_pipeline.as_ref().unwrap(),
        }
    }

    pub fn ensure_grid_plane_pipeline(&mut self) {
        if self.grid_plane_pipeline.is_none() {
            self.grid_plane_pipeline = Some(self.create_grid_plane_pipeline());
        }
    }

    pub fn grid_plane_pipeline(&self) -> Option<&wgpu::RenderPipeline> {
        self.grid_plane_pipeline.as_ref()
    }

    /// Create point rendering pipeline
    fn create_point_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Point Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::POINT.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Point Pipeline Layout"),
                bind_group_layouts: &[&self.uniform_bind_group_layout],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Point Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::PointList,
                    strip_index_format: None,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: None,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: true,
                    depth_compare: self.depth_compare(),
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    /// Create line rendering pipeline
    fn create_line_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Line Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::LINE.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Line Pipeline Layout"),
                bind_group_layouts: &[&self.uniform_bind_group_layout],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Line Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::LineList,
                    strip_index_format: None,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: None,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: true,
                    depth_compare: self.depth_compare(),
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    /// Create optimized direct rendering pipeline for precise viewport mapping
    fn create_direct_line_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Direct Line Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::LINE_DIRECT.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Direct Line Pipeline Layout"),
                bind_group_layouts: &[&self.direct_uniform_bind_group_layout],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Direct Line Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::LineList,
                    strip_index_format: None,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: None,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                // This pipeline is used inside a render pass that has a depth attachment.
                // To be compatible with that pass, we must specify a matching depth format.
                // Use CompareFunction::Always + no writes to effectively disable depth testing.
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: false,
                    depth_compare: wgpu::CompareFunction::Always,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    /// Create optimized direct triangle pipeline (2D fills) for precise viewport mapping
    fn create_direct_triangle_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Direct Triangle Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::LINE_DIRECT.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Direct Triangle Pipeline Layout"),
                bind_group_layouts: &[&self.direct_uniform_bind_group_layout],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Direct Triangle Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::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,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: false,
                    depth_compare: wgpu::CompareFunction::Always,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    /// Create optimized direct point pipeline (instanced quads per point)
    fn create_direct_point_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Direct Point Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::POINT_DIRECT.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Direct Point Pipeline Layout"),
                bind_group_layouts: &[
                    &self.direct_uniform_bind_group_layout,
                    &self.point_style_bind_group_layout,
                ],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Direct Point Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::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,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: false,
                    depth_compare: wgpu::CompareFunction::Always,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    /// Create style bind group for scatter points. Returns (buffer, bind_group).
    pub fn create_point_style_bind_group(
        &self,
        style: PointStyleUniforms,
    ) -> (wgpu::Buffer, wgpu::BindGroup) {
        let buffer = self
            .device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some("Point Style Uniform Buffer"),
                contents: bytemuck::bytes_of(&style),
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            });
        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Point Style Bind Group"),
            layout: &self.point_style_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: buffer.as_entire_binding(),
            }],
        });
        (buffer, bind_group)
    }

    /// Create textured image pipeline (direct viewport mapping + sampled texture)
    fn create_image_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Image Direct Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::IMAGE_DIRECT.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Image Pipeline Layout"),
                bind_group_layouts: &[
                    &self.direct_uniform_bind_group_layout,
                    &self.image_bind_group_layout,
                ],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Image Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::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,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: false,
                    depth_compare: wgpu::CompareFunction::Always,
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    /// Create triangle rendering pipeline
    fn create_triangle_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Triangle Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::TRIANGLE.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Triangle Pipeline Layout"),
                bind_group_layouts: &[&self.uniform_bind_group_layout],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Triangle Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::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, // Disable culling for 2D plotting
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: true,
                    depth_compare: self.depth_compare(),
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    fn create_grid_plane_pipeline(&self) -> wgpu::RenderPipeline {
        let shader = self
            .device
            .create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("Grid Plane Shader"),
                source: wgpu::ShaderSource::Wgsl(shaders::vertex::GRID_PLANE.into()),
            });

        let pipeline_layout = self
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Grid Plane Pipeline Layout"),
                bind_group_layouts: &[
                    &self.uniform_bind_group_layout,
                    &self.grid_uniform_bind_group_layout,
                ],
                push_constant_ranges: &[],
            });

        self.device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Grid Plane Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: "vs_main",
                    buffers: &[Vertex::desc()],
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: "fs_main",
                    targets: &[Some(wgpu::ColorTargetState {
                        format: self.surface_config.format,
                        blend: Some(wgpu::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,
                    polygon_mode: wgpu::PolygonMode::Fill,
                    unclipped_depth: false,
                    conservative: false,
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: Self::depth_format(),
                    depth_write_enabled: false,
                    depth_compare: self.depth_compare(),
                    stencil: wgpu::StencilState::default(),
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState {
                    count: self.msaa_sample_count,
                    mask: !0,
                    alpha_to_coverage_enabled: false,
                },
                multiview: None,
            })
    }

    /// Begin a render pass
    pub fn begin_render_pass<'a>(
        &'a self,
        encoder: &'a mut wgpu::CommandEncoder,
        view: &'a wgpu::TextureView,
        _depth_view: &'a wgpu::TextureView,
    ) -> wgpu::RenderPass<'a> {
        encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color {
                        r: 0.1,
                        g: 0.1,
                        b: 0.1,
                        a: 1.0,
                    }),
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None, // No depth testing for 2D plotting
            occlusion_query_set: None,
            timestamp_writes: None,
        })
    }

    /// Render vertices with the specified pipeline
    pub fn render_vertices<'a>(
        &'a mut self,
        render_pass: &mut wgpu::RenderPass<'a>,
        pipeline_type: PipelineType,
        vertex_buffer: &'a wgpu::Buffer,
        vertex_count: u32,
        index_buffer: Option<(&'a wgpu::Buffer, u32)>,
        indirect: Option<(&'a wgpu::Buffer, u64)>,
    ) {
        // Ensure the pipeline exists first
        self.ensure_pipeline(pipeline_type);

        // Now get the pipeline and render
        let pipeline = self.get_pipeline(pipeline_type);
        render_pass.set_pipeline(pipeline);
        render_pass.set_bind_group(0, &self.uniform_bind_group, &[]);
        render_pass.set_vertex_buffer(0, vertex_buffer.slice(..));

        if let Some((args, offset)) = indirect {
            render_pass.draw_indirect(args, offset);
            return;
        }

        match index_buffer {
            Some((indices, index_count)) => {
                render_pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32);
                render_pass.draw_indexed(0..index_count, 0, 0..1);
            }
            None => {
                render_pass.draw(0..vertex_count, 0..1);
            }
        }
    }

    /// Ensure direct line pipeline exists
    pub fn ensure_direct_line_pipeline(&mut self) {
        if self.direct_line_pipeline.is_none() {
            self.direct_line_pipeline = Some(self.create_direct_line_pipeline());
        }
    }

    /// Ensure direct triangle pipeline exists
    pub fn ensure_direct_triangle_pipeline(&mut self) {
        if self.direct_triangle_pipeline.is_none() {
            self.direct_triangle_pipeline = Some(self.create_direct_triangle_pipeline());
        }
    }

    /// Ensure direct point pipeline exists
    pub fn ensure_direct_point_pipeline(&mut self) {
        if self.direct_point_pipeline.is_none() {
            self.direct_point_pipeline = Some(self.create_direct_point_pipeline());
        }
    }

    /// Ensure image pipeline exists
    pub fn ensure_image_pipeline(&mut self) {
        if self.image_pipeline.is_none() {
            self.image_pipeline = Some(self.create_image_pipeline());
        }
    }

    /// Update transformation uniforms for direct viewport rendering
    pub fn update_direct_uniforms(
        &mut self,
        data_min: [f32; 2],
        data_max: [f32; 2],
        viewport_min: [f32; 2],
        viewport_max: [f32; 2],
        viewport_px: [f32; 2],
    ) {
        self.direct_uniforms =
            DirectUniforms::new(data_min, data_max, viewport_min, viewport_max, viewport_px);
        self.queue.write_buffer(
            &self.direct_uniform_buffer,
            0,
            bytemuck::cast_slice(&[self.direct_uniforms]),
        );
        self.ensure_axes_uniform_capacity(1);
        self.queue.write_buffer(
            &self.axes_direct_uniform_buffers[0],
            0,
            bytemuck::cast_slice(&[self.direct_uniforms]),
        );
    }

    pub fn update_direct_uniforms_for_axes(
        &mut self,
        axes_index: usize,
        data_min: [f32; 2],
        data_max: [f32; 2],
        viewport_min: [f32; 2],
        viewport_max: [f32; 2],
        viewport_px: [f32; 2],
    ) {
        self.ensure_axes_uniform_capacity(axes_index + 1);
        let uniforms =
            DirectUniforms::new(data_min, data_max, viewport_min, viewport_max, viewport_px);
        self.queue.write_buffer(
            &self.axes_direct_uniform_buffers[axes_index],
            0,
            bytemuck::cast_slice(&[uniforms]),
        );
    }

    pub fn get_direct_uniform_bind_group_for_axes(&self, axes_index: usize) -> &wgpu::BindGroup {
        self.axes_direct_uniform_bind_groups
            .get(axes_index)
            .unwrap_or(&self.direct_uniform_bind_group)
    }
}

/// Utility functions for creating common vertex patterns
pub mod vertex_utils {
    use super::*;
    use glam::Vec2;

    /// Create vertices for a line from start to end point
    pub fn create_line(start: Vec3, end: Vec3, color: Vec4) -> Vec<Vertex> {
        vec![Vertex::new(start, color), Vertex::new(end, color)]
    }

    /// CPU polyline extrusion for thick lines (butt caps, miter joins simplified)
    /// Input: contiguous points. Output: triangle list vertices.
    pub fn extrude_polyline(points: &[Vec3], color: Vec4, width: f32) -> Vec<Vertex> {
        let mut out: Vec<Vertex> = Vec::new();
        if points.len() < 2 {
            return out;
        }
        // `width` is expected to already be in data-space units. Do NOT clamp to 1.0 here:
        // plot axes ranges are often small (e.g. y in [-1,1]), and clamping would explode
        // thick line geometry into a huge filled shape.
        let half_w = width.max(0.0) * 0.5;
        for i in 0..points.len() - 1 {
            let p0 = points[i];
            let p1 = points[i + 1];
            let dir = (p1 - p0).truncate();
            let len = (dir.x * dir.x + dir.y * dir.y).sqrt().max(1e-6);
            let nx = -dir.y / len;
            let ny = dir.x / len;
            let offset = Vec3::new(nx * half_w, ny * half_w, 0.0);
            // Quad corners in CCW
            let a = p0 - offset;
            let b = p0 + offset;
            let c = p1 + offset;
            let d = p1 - offset;
            // Two triangles: a-b-c and a-c-d
            out.push(Vertex::new(a, color));
            out.push(Vertex::new(b, color));
            out.push(Vertex::new(c, color));
            out.push(Vertex::new(a, color));
            out.push(Vertex::new(c, color));
            out.push(Vertex::new(d, color));
        }
        out
    }

    fn line_intersection(p: Vec2, r: Vec2, q: Vec2, s: Vec2) -> Option<Vec2> {
        let rxs = r.perp_dot(s);
        if rxs.abs() < 1e-6 {
            return None;
        }
        let t = (q - p).perp_dot(s) / rxs;
        Some(p + r * t)
    }

    /// Extrude polyline with join styles at internal vertices.
    pub fn extrude_polyline_with_join(
        points: &[Vec3],
        color: Vec4,
        width: f32,
        join: crate::plots::line::LineJoin,
    ) -> Vec<Vertex> {
        let mut out: Vec<Vertex> = Vec::new();
        if points.len() < 2 {
            return out;
        }
        // See `extrude_polyline` for rationale: keep width in data-space units.
        let half_w = width.max(0.0) * 0.5;
        // Base quads
        out.extend(extrude_polyline(points, color, width));

        // Joins
        for i in 1..points.len() - 1 {
            let p_prev = points[i - 1];
            let p = points[i];
            let p_next = points[i + 1];
            let d0 = (p - p_prev).truncate();
            let d1 = (p_next - p).truncate();
            let l0 = d0.length().max(1e-6);
            let l1 = d1.length().max(1e-6);
            let n0 = Vec2::new(-d0.y / l0, d0.x / l0);
            let n1 = Vec2::new(-d1.y / l1, d1.x / l1);
            let turn = d0.perp_dot(d1); // >0 left turn, <0 right turn

            if turn > 1e-6 {
                // Left turn: outer side is left (use +n)
                let left0 = p.truncate() + n0 * half_w;
                let left1 = p.truncate() + n1 * half_w;
                match join {
                    crate::plots::line::LineJoin::Bevel => {
                        // Triangle wedge (p, left0, left1)
                        out.push(Vertex::new(p, color));
                        out.push(Vertex::new(left0.extend(0.0), color));
                        out.push(Vertex::new(left1.extend(0.0), color));
                    }
                    crate::plots::line::LineJoin::Miter => {
                        let dir_edge0 = (p.truncate() - p_prev.truncate()).normalize_or_zero();
                        let dir_edge1 = (p_next.truncate() - p.truncate()).normalize_or_zero();
                        let l_edge = line_intersection(left0, dir_edge0, left1, dir_edge1);
                        if let Some(miter) = l_edge {
                            // fill wedge left0-miter-left1
                            out.push(Vertex::new(left0.extend(0.0), color));
                            out.push(Vertex::new(miter.extend(0.0), color));
                            out.push(Vertex::new(left1.extend(0.0), color));
                        } else {
                            // fallback to bevel
                            out.push(Vertex::new(p, color));
                            out.push(Vertex::new(left0.extend(0.0), color));
                            out.push(Vertex::new(left1.extend(0.0), color));
                        }
                    }
                    crate::plots::line::LineJoin::Round => {
                        // Arc fan from left0 -> left1 around p
                        let center = p.truncate();
                        let a0 = (left0 - center).to_array();
                        let a1 = (left1 - center).to_array();
                        let ang0 = a0[1].atan2(a0[0]);
                        let mut ang1 = a1[1].atan2(a1[0]);
                        // Ensure CCW sweep
                        if ang1 < ang0 {
                            ang1 += std::f32::consts::TAU;
                        }
                        let steps = 10usize;
                        let dtheta = (ang1 - ang0) / steps as f32;
                        let r = half_w;
                        for k in 0..steps {
                            let theta0 = ang0 + dtheta * k as f32;
                            let theta1 = ang0 + dtheta * (k + 1) as f32;
                            let v0 =
                                Vec2::new(center.x + theta0.cos() * r, center.y + theta0.sin() * r);
                            let v1 =
                                Vec2::new(center.x + theta1.cos() * r, center.y + theta1.sin() * r);
                            out.push(Vertex::new(p, color));
                            out.push(Vertex::new(v0.extend(0.0), color));
                            out.push(Vertex::new(v1.extend(0.0), color));
                        }
                    }
                }
            } else if turn < -1e-6 {
                // Right turn: outer side is right (use -n)
                let right0 = p.truncate() - n0 * half_w;
                let right1 = p.truncate() - n1 * half_w;
                match join {
                    crate::plots::line::LineJoin::Bevel => {
                        out.push(Vertex::new(p, color));
                        out.push(Vertex::new(right1.extend(0.0), color));
                        out.push(Vertex::new(right0.extend(0.0), color));
                    }
                    crate::plots::line::LineJoin::Miter => {
                        let dir_edge0 = (p.truncate() - p_prev.truncate()).normalize_or_zero();
                        let dir_edge1 = (p_next.truncate() - p.truncate()).normalize_or_zero();
                        let l_edge = line_intersection(right0, dir_edge0, right1, dir_edge1);
                        if let Some(miter) = l_edge {
                            out.push(Vertex::new(right1.extend(0.0), color));
                            out.push(Vertex::new(miter.extend(0.0), color));
                            out.push(Vertex::new(right0.extend(0.0), color));
                        } else {
                            out.push(Vertex::new(p, color));
                            out.push(Vertex::new(right1.extend(0.0), color));
                            out.push(Vertex::new(right0.extend(0.0), color));
                        }
                    }
                    crate::plots::line::LineJoin::Round => {
                        let center = p.truncate();
                        let a0 = (right0 - center).to_array();
                        let a1 = (right1 - center).to_array();
                        let mut ang0 = a0[1].atan2(a0[0]);
                        let mut ang1 = a1[1].atan2(a1[0]);
                        // Ensure CW sweep becomes CCW by swapping
                        if ang0 < ang1 {
                            std::mem::swap(&mut ang0, &mut ang1);
                        }
                        let steps = 10usize;
                        let dtheta = (ang0 - ang1) / steps as f32;
                        let r = half_w;
                        for k in 0..steps {
                            let theta0 = ang0 - dtheta * k as f32;
                            let theta1 = ang0 - dtheta * (k + 1) as f32;
                            let v0 =
                                Vec2::new(center.x + theta0.cos() * r, center.y + theta0.sin() * r);
                            let v1 =
                                Vec2::new(center.x + theta1.cos() * r, center.y + theta1.sin() * r);
                            out.push(Vertex::new(p, color));
                            out.push(Vertex::new(v0.extend(0.0), color));
                            out.push(Vertex::new(v1.extend(0.0), color));
                        }
                    }
                }
            }
        }

        out
    }

    /// Create vertices for a triangle
    pub fn create_triangle(p1: Vec3, p2: Vec3, p3: Vec3, color: Vec4) -> Vec<Vertex> {
        vec![
            Vertex::new(p1, color),
            Vertex::new(p2, color),
            Vertex::new(p3, color),
        ]
    }

    /// Create vertices for a point cloud
    pub fn create_point_cloud(points: &[Vec3], colors: &[Vec4]) -> Vec<Vertex> {
        points
            .iter()
            .zip(colors.iter())
            .map(|(&pos, &color)| Vertex::new(pos, color))
            .collect()
    }

    /// Create vertices for a parametric line plot (1px line segments)
    pub fn create_line_plot(x_data: &[f64], y_data: &[f64], color: Vec4) -> Vec<Vertex> {
        let mut vertices = Vec::new();

        for i in 1..x_data.len() {
            let start = Vec3::new(x_data[i - 1] as f32, y_data[i - 1] as f32, 0.0);
            let end = Vec3::new(x_data[i] as f32, y_data[i] as f32, 0.0);
            vertices.extend(create_line(start, end, color));
        }

        vertices
    }

    /// Create dashed/dotted line vertices by selectively including segments.
    /// Approximation: pattern is applied per original segment index.
    pub fn create_line_plot_dashed(
        x_data: &[f64],
        y_data: &[f64],
        color: Vec4,
        style: crate::plots::line::LineStyle,
    ) -> Vec<Vertex> {
        let mut vertices = Vec::new();
        for i in 1..x_data.len() {
            let include = match style {
                crate::plots::line::LineStyle::Solid => true,
                crate::plots::line::LineStyle::Dashed => (i % 4) < 2, // on,on,off,off
                crate::plots::line::LineStyle::Dotted => false,       // handled elsewhere as points
                crate::plots::line::LineStyle::DashDot => {
                    let m = i % 6;
                    m < 2 || m == 3 // on,on,off,on,off,off
                }
            };
            if include {
                let start = Vec3::new(x_data[i - 1] as f32, y_data[i - 1] as f32, 0.0);
                let end = Vec3::new(x_data[i] as f32, y_data[i] as f32, 0.0);
                vertices.extend(create_line(start, end, color));
            }
        }
        vertices
    }

    /// Create thick polyline as triangles (used when line width > 1)
    pub fn create_thick_polyline(
        x_data: &[f64],
        y_data: &[f64],
        color: Vec4,
        width_px: f32,
    ) -> Vec<Vertex> {
        let mut pts: Vec<Vec3> = Vec::with_capacity(x_data.len());
        for i in 0..x_data.len() {
            pts.push(Vec3::new(x_data[i] as f32, y_data[i] as f32, 0.0));
        }
        extrude_polyline(&pts, color, width_px)
    }

    /// Thick polyline with join style
    pub fn create_thick_polyline_with_join(
        x_data: &[f64],
        y_data: &[f64],
        color: Vec4,
        width_px: f32,
        join: crate::plots::line::LineJoin,
    ) -> Vec<Vertex> {
        let mut pts: Vec<Vec3> = Vec::with_capacity(x_data.len());
        for i in 0..x_data.len() {
            pts.push(Vec3::new(x_data[i] as f32, y_data[i] as f32, 0.0));
        }
        extrude_polyline_with_join(&pts, color, width_px, join)
    }

    /// Create dashed/dotted thick polyline by skipping segments in the extruder.
    pub fn create_thick_polyline_dashed(
        x_data: &[f64],
        y_data: &[f64],
        color: Vec4,
        width_px: f32,
        style: crate::plots::line::LineStyle,
    ) -> Vec<Vertex> {
        let mut out: Vec<Vertex> = Vec::new();
        if x_data.len() < 2 {
            return out;
        }
        let pts: Vec<Vec3> = x_data
            .iter()
            .zip(y_data.iter())
            .map(|(&x, &y)| Vec3::new(x as f32, y as f32, 0.0))
            .collect();
        for i in 0..pts.len() - 1 {
            let include = match style {
                crate::plots::line::LineStyle::Solid => true,
                crate::plots::line::LineStyle::Dashed => (i % 4) < 2,
                crate::plots::line::LineStyle::Dotted => false,
                crate::plots::line::LineStyle::DashDot => {
                    let m = i % 6;
                    m < 2 || m == 3
                }
            };
            if include {
                let seg = [pts[i], pts[i + 1]];
                out.extend(extrude_polyline(&seg, color, width_px));
            }
        }
        out
    }

    /// Square caps variant: extend endpoints by half width
    pub fn create_thick_polyline_square_caps(
        x_data: &[f64],
        y_data: &[f64],
        color: Vec4,
        width_px: f32,
    ) -> Vec<Vertex> {
        if x_data.len() < 2 {
            return Vec::new();
        }
        let mut pts: Vec<Vec3> = Vec::with_capacity(x_data.len());
        for i in 0..x_data.len() {
            pts.push(Vec3::new(x_data[i] as f32, y_data[i] as f32, 0.0));
        }
        // extend start
        let dir0 = (pts[1] - pts[0]).truncate();
        let len0 = (dir0.x * dir0.x + dir0.y * dir0.y).sqrt().max(1e-6);
        let ext0 = Vec3::new(
            -(dir0.x / len0) * (width_px * 0.5),
            -(dir0.y / len0) * (width_px * 0.5),
            0.0,
        );
        pts[0] += ext0;
        // extend end
        let n = pts.len();
        let dir1 = (pts[n - 1] - pts[n - 2]).truncate();
        let len1 = (dir1.x * dir1.x + dir1.y * dir1.y).sqrt().max(1e-6);
        let ext1 = Vec3::new(
            (dir1.x / len1) * (width_px * 0.5),
            (dir1.y / len1) * (width_px * 0.5),
            0.0,
        );
        pts[n - 1] += ext1;
        extrude_polyline(&pts, color, width_px)
    }

    /// Round caps variant: square caps plus approximated semicircle fan at ends
    pub fn create_thick_polyline_round_caps(
        x_data: &[f64],
        y_data: &[f64],
        color: Vec4,
        width_px: f32,
        segments: usize,
    ) -> Vec<Vertex> {
        let mut base = create_thick_polyline_square_caps(x_data, y_data, color, width_px);
        if x_data.len() < 2 {
            return base;
        }
        let r = width_px * 0.5;
        // start fan
        let p0 = Vec3::new(x_data[0] as f32, y_data[0] as f32, 0.0);
        let p1 = Vec3::new(x_data[1] as f32, y_data[1] as f32, 0.0);
        let dir0 = (p1 - p0).truncate();
        let theta0 = dir0.y.atan2(dir0.x) + std::f32::consts::PI; // facing backward
        for i in 0..segments {
            let a0 = theta0 - std::f32::consts::PI * (i as f32 / segments as f32);
            let a1 = theta0 - std::f32::consts::PI * ((i + 1) as f32 / segments as f32);
            let v0 = Vec3::new(p0.x + a0.cos() * r, p0.y + a0.sin() * r, 0.0);
            let v1 = Vec3::new(p0.x + a1.cos() * r, p0.y + a1.sin() * r, 0.0);
            base.push(Vertex::new(p0, color));
            base.push(Vertex::new(v0, color));
            base.push(Vertex::new(v1, color));
        }
        // end fan
        let n = x_data.len();
        let q0 = Vec3::new(x_data[n - 2] as f32, y_data[n - 2] as f32, 0.0);
        let q1 = Vec3::new(x_data[n - 1] as f32, y_data[n - 1] as f32, 0.0);
        let dir1 = (q1 - q0).truncate();
        let theta1 = dir1.y.atan2(dir1.x);
        let center = q1;
        for i in 0..segments {
            let a0 = theta1 - std::f32::consts::PI * (i as f32 / segments as f32);
            let a1 = theta1 - std::f32::consts::PI * ((i + 1) as f32 / segments as f32);
            let v0 = Vec3::new(center.x + a0.cos() * r, center.y + a0.sin() * r, 0.0);
            let v1 = Vec3::new(center.x + a1.cos() * r, center.y + a1.sin() * r, 0.0);
            base.push(Vertex::new(center, color));
            base.push(Vertex::new(v0, color));
            base.push(Vertex::new(v1, color));
        }
        base
    }

    /// Create vertices for a scatter plot
    pub fn create_scatter_plot(x_data: &[f64], y_data: &[f64], color: Vec4) -> Vec<Vertex> {
        x_data
            .iter()
            .zip(y_data.iter())
            .map(|(&x, &y)| Vertex::new(Vec3::new(x as f32, y as f32, 0.0), color))
            .collect()
    }
}