charton 0.5.8

A high-performance, layered charting system for Rust, featuring a flexible data core and multi-backend rendering.
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
//! WGPU rendering backend implementation for 2D primitive rendering
//! Provides GPU-optimized data structures and render pipelines aligned with WGSL shaders
//!
//! Architecture: Two-Tier Bind Group Design
//! - @group(0): Global Environment (Uniforms shared across all pipelines)
//! - @group(1): Isolated Instance Data (Exclusive storage buffers per pipeline)

use crate::core::layer::{
    CircleConfig, GradientRectConfig, LineConfig, PathConfig, PathTopology, PolygonConfig,
    RectConfig, RenderBackend, TextConfig,
};
use bytemuck::{Pod, Zeroable};
use wgpu::util::DeviceExt;

// ============================================================================
// GPU Data Structures (Strict 1:1 WGSL Alignment - std140 layout)
// ============================================================================

/// Base data for instanced SDF primitives (matches PointData in WGSL)
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct GpuPoint {
    pub x: f32,
    pub y: f32,
    pub fill_r: f32,
    pub fill_g: f32,
    pub fill_b: f32,
    pub fill_a: f32,
    pub stroke_r: f32,
    pub stroke_g: f32,
    pub stroke_b: f32,
    pub stroke_a: f32,
    pub radius: f32,
    pub stroke_width: f32,
}

/// GPU data structure for rectangle primitives (matches RectData in WGSL)
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct GpuRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub fill_r: f32,
    pub fill_g: f32,
    pub fill_b: f32,
    pub fill_a: f32,
    pub stroke_r: f32,
    pub stroke_g: f32,
    pub stroke_b: f32,
    pub stroke_a: f32,
    pub stroke_width: f32,
    pub corner_radius: f32,
}

/// GPU data structure for line primitives (matches LineData in WGSL)
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct GpuLine {
    pub x1: f32,
    pub y1: f32,
    pub x2: f32,
    pub y2: f32,
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
    pub width: f32,
    pub _pad1: f32,
    pub _pad2: f32,
    pub _pad3: f32,
}

/// GPU data structure for gradient-filled rectangles (matches GradientRectData in WGSL)
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct GpuGradientRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    start_r: f32,
    start_g: f32,
    start_b: f32,
    start_a: f32,
    end_r: f32,
    end_g: f32,
    end_b: f32,
    end_a: f32,
    pub angle: f32,
    pub opacity: f32,
}

// ----------------------------------------------------------------------------
// Pure GPU Polyline Extrusion Layouts (Path Stream)
// ----------------------------------------------------------------------------

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct GpuPathPoint {
    pub x: f32,
    pub y: f32,
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct GpuPathStyle {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
    pub thickness: f32,
    pub _pad0: f32,
    pub _pad1: f32,
    pub _pad2: f32,
}

#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct GpuPathArgs {
    pub start_point_idx: u32,
    pub style_idx: u32,
    pub _pad0: u32,
    pub _pad1: u32,
}

/// Vertex data for polygon primitives (matches CPU-generated stream)
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct PathVertex {
    pub position: [f32; 2],
    pub color: [f32; 4],
    pub is_fill: f32,
}

impl PathVertex {
    pub const DESC: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
        step_mode: wgpu::VertexStepMode::Vertex,
        attributes: &[
            wgpu::VertexAttribute {
                offset: 0,
                shader_location: 0,
                format: wgpu::VertexFormat::Float32x2,
            },
            wgpu::VertexAttribute {
                offset: std::mem::size_of::<[f32; 2]>() as wgpu::BufferAddress,
                shader_location: 1,
                format: wgpu::VertexFormat::Float32x4,
            },
            wgpu::VertexAttribute {
                offset: (std::mem::size_of::<[f32; 2]>() + std::mem::size_of::<[f32; 4]>())
                    as wgpu::BufferAddress,
                shader_location: 2,
                format: wgpu::VertexFormat::Float32,
            },
        ],
    };
}

/// Global uniform data for all shaders (strict std140 alignment)
#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
pub struct Uniforms {
    pub screen_width: f32,
    pub screen_height: f32,
    pub scale_factor: f32,
    pub _padding: f32,
}

#[derive(Debug, Clone, Copy)]
pub enum DrawBatch {
    Circle { start: u32, count: u32 },
    Rect { start: u32, count: u32 },
    Line { start: u32, count: u32 },
    Polygon { index_start: u32, index_count: u32 },
    GradientRect { start: u32, count: u32 },
    PathSimple { path_idx: u32, point_count: u32 },
    PathComplexStencil { index_start: u32, index_count: u32 },
    PathComplexCover { index_start: u32, index_count: u32 },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BatchType {
    Circle,
    Rect,
    Line,
    Polygon,
    GradientRect,
    PathComplexStencil,
    PathComplexCover,
}

// ============================================================================
// WGPU Backend Core Implementation
// ============================================================================

pub struct WgpuBackend {
    device: wgpu::Device,
    queue: wgpu::Queue,

    // Global uniform buffer
    uniform_buffer: wgpu::Buffer,

    // Two-Tier Architecture Bind Group Definitions
    global_bind_group: wgpu::BindGroup,
    global_bind_group_layout: wgpu::BindGroupLayout,
    instance_bind_group_layout: wgpu::BindGroupLayout,

    // Circle primitive resources
    circle_pipeline: wgpu::RenderPipeline,
    circle_buffer: wgpu::Buffer,
    pending_circles: Vec<GpuPoint>,
    uploaded_circle_count: u32,

    // Rectangle primitive resources
    rect_pipeline: wgpu::RenderPipeline,
    rect_buffer: wgpu::Buffer,
    pending_rects: Vec<GpuRect>,
    uploaded_rect_count: u32,

    // Line primitive resources
    line_pipeline: wgpu::RenderPipeline,
    line_buffer: wgpu::Buffer,
    pending_lines: Vec<GpuLine>,
    uploaded_line_count: u32,

    // Polygon primitive resources
    polygon_pipeline: wgpu::RenderPipeline,
    complex_stencil_pipeline: wgpu::RenderPipeline, // For irregular polygons using stencil buffering
    complex_cover_pipeline: wgpu::RenderPipeline, // For irregular polygons using cover pass after stencil masking
    polygon_vertex_buffer: wgpu::Buffer,
    polygon_index_buffer: wgpu::Buffer,
    pending_polygon_vertices: Vec<PathVertex>,
    pending_polygon_indices: Vec<u16>,
    uploaded_polygon_index_count: u32,

    // Gradient rectangle resources
    gradient_rect_pipeline: wgpu::RenderPipeline,
    gradient_rect_buffer: wgpu::Buffer,
    pending_gradient_rects: Vec<GpuGradientRect>,
    uploaded_gradient_rect_count: u32,

    // Path primitive resources
    path_simple_pipeline: wgpu::RenderPipeline,
    path_bind_group_layout: wgpu::BindGroupLayout,
    pending_path_points: Vec<GpuPathPoint>,
    pending_path_styles: Vec<GpuPathStyle>,
    pending_path_args: Vec<GpuPathArgs>,

    pub collected_texts: Vec<TextConfig>,
    // A tuple containing the batch and its associated scissor state.
    #[allow(clippy::type_complexity)]
    batches: Vec<(DrawBatch, Option<(u32, u32, u32, u32)>)>,
    // Add state tracking for physical dimensions and current clipping rect.
    current_scissor: Option<(u32, u32, u32, u32)>,
    // Physical width of the rendering surface in device pixels (logical_width * scale_factor).
    // Used for scissor rect clamping and full-screen restore operations.
    physical_width: u32,
    // Physical height of the rendering surface in device pixels (logical_height * scale_factor).
    // Used for scissor rect clamping and full-screen restore operations.
    physical_height: u32,
    scale_factor: f32,

    current_circle_count: u32,
    current_rect_count: u32,
    current_line_count: u32,
    current_polygon_index_count: u32,
    current_grad_rect_count: u32,

    // Invisible mask canvas used by the GPU to calculate complex polygon fills.
    depth_stencil_view: wgpu::TextureView,
}

impl WgpuBackend {
    pub async fn new(
        device: wgpu::Device,
        queue: wgpu::Queue,
        screen_width: u32,
        screen_height: u32,
        scale_factor: f32,
    ) -> Self {
        let shader = device.create_shader_module(wgpu::include_wgsl!("chart.wgsl"));

        let uniforms = Uniforms {
            screen_width: screen_width as f32,
            screen_height: screen_height as f32,
            scale_factor,
            _padding: 0.0,
        };
        let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("Uniform Buffer - Group 0"),
            contents: bytemuck::cast_slice(&[uniforms]),
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
        });

        // ====================================================================
        // RESOURCE BIND GROUP LAYOUT DECLARATIONS (Scientific Architecture)
        // ====================================================================

        // Group 0: Global Environment (Uniforms)
        let global_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Global Environment Bind Group Layout 0"),
                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,
                }],
            });

        // Group 1: Universal Instance Data (Circles, Rects, Lines, Gradients)
        let instance_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Universal Instance Bind Group Layout 1"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });

        // Path stream layout (Group 1 with 3 decoupled slots)
        let path_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("Path Storage Bind Group Layout 1"),
                entries: &[
                    wgpu::BindGroupLayoutEntry {
                        binding: 0,
                        visibility: wgpu::ShaderStages::VERTEX,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Storage { read_only: true },
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 1,
                        visibility: wgpu::ShaderStages::VERTEX,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Storage { read_only: true },
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                    wgpu::BindGroupLayoutEntry {
                        binding: 2,
                        visibility: wgpu::ShaderStages::VERTEX,
                        ty: wgpu::BindingType::Buffer {
                            ty: wgpu::BufferBindingType::Storage { read_only: true },
                            has_dynamic_offset: false,
                            min_binding_size: None,
                        },
                        count: None,
                    },
                ],
            });

        // Create the initial global bind group state
        let global_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Global Environment Bind Group 0"),
            layout: &global_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(uniform_buffer.as_entire_buffer_binding()),
            }],
        });

        // ====================================================================
        // RENDER PIPELINES COMPILATION
        // ====================================================================
        let circle_pipeline = Self::create_circle_pipeline(
            &device,
            &shader,
            &global_bind_group_layout,
            &instance_bind_group_layout,
        );
        let line_pipeline = Self::create_line_pipeline(
            &device,
            &shader,
            &global_bind_group_layout,
            &instance_bind_group_layout,
        );
        let rect_pipeline = Self::create_rect_pipeline(
            &device,
            &shader,
            &global_bind_group_layout,
            &instance_bind_group_layout,
        );
        let polygon_pipeline = Self::create_polygon_pipeline(
            &device,
            &shader,
            &global_bind_group_layout, // Polygon only needs Group 0
        );
        let gradient_rect_pipeline = Self::create_gradient_rect_pipeline(
            &device,
            &shader,
            &global_bind_group_layout,
            &instance_bind_group_layout,
        );

        // Path Simple Pipeline
        let path_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Path Simple Pipeline Layout"),
            bind_group_layouts: &[
                Some(&global_bind_group_layout),
                Some(&path_bind_group_layout),
            ],
            immediate_size: 0,
        });

        let path_simple_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Path Hardware Extrusion Pipeline"),
            layout: Some(&path_pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("path_simple_vs"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("path_simple_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            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,
            },
            // Match pass format for compatibility, but bypass actual testing for non-polygon pipelines
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Always),
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState::IGNORE,
                    back: wgpu::StencilFaceState::IGNORE,
                    read_mask: 0,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });

        // Complex Path Pipeline
        // Shared pipeline layout utilizing only global environment uniforms
        let complex_path_pipeline_layout =
            device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Complex Path Pipeline Layout"),
                bind_group_layouts: &[Some(&global_bind_group_layout)],
                immediate_size: 0,
            });

        // PASS 1: STENCIL PIPELINE - Generates the polygon mask via odd-even inversion (Color write disabled)
        let complex_stencil_pipeline =
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Complex Path - Stencil Pass Pipeline"),
                layout: Some(&complex_path_pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: Some("polygon_vs"),
                    buffers: &[PathVertex::DESC],
                    compilation_options: Default::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: Some("polygon_fs"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: wgpu::TextureFormat::Rgba8Unorm,
                        blend: None,
                        write_mask: wgpu::ColorWrites::empty(), // No color writes completely for the stencil pass
                    })],
                    compilation_options: Default::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: None,
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth24PlusStencil8,
                    depth_write_enabled: Some(false),
                    depth_compare: Some(wgpu::CompareFunction::Always),
                    stencil: wgpu::StencilState {
                        // Invert bits on pass to natively resolve self-intersections and concavity
                        front: wgpu::StencilFaceState {
                            compare: wgpu::CompareFunction::Always,
                            fail_op: wgpu::StencilOperation::Keep,
                            depth_fail_op: wgpu::StencilOperation::Keep,
                            pass_op: wgpu::StencilOperation::Invert,
                        },
                        back: wgpu::StencilFaceState {
                            compare: wgpu::CompareFunction::Always,
                            fail_op: wgpu::StencilOperation::Keep,
                            depth_fail_op: wgpu::StencilOperation::Keep,
                            pass_op: wgpu::StencilOperation::Invert,
                        },
                        read_mask: 0xFF,
                        write_mask: 0xFF,
                    },
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            });

        // PASS 2: COVER PIPELINE - Rasterizes the bounding color quad, filling and auto-clearing the masked region
        let complex_cover_pipeline =
            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Complex Path - Cover Pass Pipeline"),
                layout: Some(&complex_path_pipeline_layout),
                vertex: wgpu::VertexState {
                    module: &shader,
                    entry_point: Some("polygon_vs"),
                    buffers: &[PathVertex::DESC],
                    compilation_options: Default::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: &shader,
                    entry_point: Some("polygon_fs"),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: wgpu::TextureFormat::Rgba8Unorm,
                        blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                        write_mask: wgpu::ColorWrites::ALL, // Restore color channel writing
                    })],
                    compilation_options: Default::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    front_face: wgpu::FrontFace::Ccw,
                    cull_mode: None,
                    ..Default::default()
                },
                depth_stencil: Some(wgpu::DepthStencilState {
                    format: wgpu::TextureFormat::Depth24PlusStencil8,
                    depth_write_enabled: Some(false),
                    depth_compare: Some(wgpu::CompareFunction::Always),
                    stencil: wgpu::StencilState {
                        // Render color where stencil is non-zero, resetting it to zero simultaneously
                        front: wgpu::StencilFaceState {
                            compare: wgpu::CompareFunction::NotEqual,
                            fail_op: wgpu::StencilOperation::Keep,
                            depth_fail_op: wgpu::StencilOperation::Keep,
                            pass_op: wgpu::StencilOperation::Zero,
                        },
                        back: wgpu::StencilFaceState {
                            compare: wgpu::CompareFunction::NotEqual,
                            fail_op: wgpu::StencilOperation::Keep,
                            depth_fail_op: wgpu::StencilOperation::Keep,
                            pass_op: wgpu::StencilOperation::Zero,
                        },
                        read_mask: 0xFF,
                        write_mask: 0xFF,
                    },
                    bias: wgpu::DepthBiasState::default(),
                }),
                multisample: wgpu::MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            });

        // Dummy buffers for initialization
        let circle_buffer = Self::create_dummy_buffer::<GpuPoint>(&device);
        let rect_buffer = Self::create_dummy_buffer::<GpuRect>(&device);
        let line_buffer = Self::create_dummy_buffer::<GpuLine>(&device);
        let gradient_rect_buffer = Self::create_dummy_buffer::<GpuGradientRect>(&device);
        let dummy_polygon_vertices = Self::create_dummy_buffer::<PathVertex>(&device);
        let dummy_polygon_indices = Self::create_dummy_buffer::<u16>(&device);

        // STENCIL MASK BUFFER FOR HETEROGENEOUS VECTOR FILLS
        let physical_width = (screen_width as f32 * scale_factor).round() as u32;
        let physical_height = (screen_height as f32 * scale_factor).round() as u32;
        let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("2D Vector Stencil Texture"),
            size: wgpu::Extent3d {
                width: physical_width,
                height: physical_height,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Depth24PlusStencil8,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        });

        // Invisible mask canvas used by the GPU to calculate complex polygon fills.
        let depth_stencil_view = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());

        Self {
            device,
            queue,
            uniform_buffer,
            global_bind_group,
            global_bind_group_layout,
            instance_bind_group_layout,

            circle_pipeline,
            circle_buffer,
            pending_circles: Vec::with_capacity(30_000),
            uploaded_circle_count: 0,

            rect_pipeline,
            rect_buffer,
            pending_rects: Vec::with_capacity(10_000),
            uploaded_rect_count: 0,

            line_pipeline,
            line_buffer,
            pending_lines: Vec::with_capacity(10_000),
            uploaded_line_count: 0,

            polygon_pipeline,
            complex_stencil_pipeline,
            complex_cover_pipeline,
            polygon_vertex_buffer: dummy_polygon_vertices,
            polygon_index_buffer: dummy_polygon_indices,
            pending_polygon_vertices: Vec::with_capacity(50_000),
            pending_polygon_indices: Vec::with_capacity(100_000),
            uploaded_polygon_index_count: 0,

            gradient_rect_pipeline,
            gradient_rect_buffer,
            pending_gradient_rects: Vec::with_capacity(10_000),
            uploaded_gradient_rect_count: 0,

            path_simple_pipeline,
            path_bind_group_layout,
            pending_path_points: Vec::with_capacity(100_000),
            pending_path_styles: Vec::with_capacity(1024),
            pending_path_args: Vec::with_capacity(1024),

            collected_texts: Vec::new(),
            batches: Vec::with_capacity(1024),
            current_scissor: None,
            physical_width,
            physical_height,
            scale_factor,

            current_circle_count: 0,
            current_rect_count: 0,
            current_line_count: 0,
            current_polygon_index_count: 0,
            current_grad_rect_count: 0,

            depth_stencil_view,
        }
    }

    /// Pushes a new draw command or merges it into the active batch to optimize GPU draw calls.
    fn push_batch(&mut self, batch_type: BatchType, count: u32) {
        // BATCH MERGING: Only merge if the primitive type AND the scissor clipping state are identical.
        let can_merge = self
            .batches
            .last()
            .is_some_and(|(_, scissor)| *scissor == self.current_scissor);

        if can_merge && let Some((last_batch, _)) = self.batches.last_mut() {
            match (last_batch, batch_type) {
                (DrawBatch::Circle { count: c, .. }, BatchType::Circle) => {
                    *c += count;
                    return;
                }
                (DrawBatch::Rect { count: c, .. }, BatchType::Rect) => {
                    *c += count;
                    return;
                }
                (DrawBatch::Line { count: c, .. }, BatchType::Line) => {
                    *c += count;
                    return;
                }
                (DrawBatch::Polygon { index_count: c, .. }, BatchType::Polygon) => {
                    *c += count;
                    return;
                }
                (DrawBatch::GradientRect { count: c, .. }, BatchType::GradientRect) => {
                    *c += count;
                    return;
                }
                (
                    DrawBatch::PathComplexStencil { index_count: c, .. },
                    BatchType::PathComplexStencil,
                ) => {
                    *c += count;
                    return;
                }
                (
                    DrawBatch::PathComplexCover { index_count: c, .. },
                    BatchType::PathComplexCover,
                ) => {
                    *c += count;
                    return;
                }
                _ => {} // PathSimple and other types fall through to isolation
            }
        }

        // FALLBACK / ISOLATION: Create a new draw batch paired with the current active scissor state.
        let new_batch = match batch_type {
            BatchType::Circle => DrawBatch::Circle {
                start: self.current_circle_count.saturating_sub(count),
                count,
            },
            BatchType::Rect => DrawBatch::Rect {
                start: self.current_rect_count.saturating_sub(count),
                count,
            },
            BatchType::Line => DrawBatch::Line {
                start: self.current_line_count.saturating_sub(count),
                count,
            },
            BatchType::Polygon => DrawBatch::Polygon {
                index_start: self.current_polygon_index_count.saturating_sub(count),
                index_count: count,
            },
            BatchType::GradientRect => DrawBatch::GradientRect {
                start: self.current_grad_rect_count.saturating_sub(count),
                count,
            },
            BatchType::PathComplexStencil => DrawBatch::PathComplexStencil {
                index_start: self.current_polygon_index_count.saturating_sub(count),
                index_count: count,
            },
            BatchType::PathComplexCover => DrawBatch::PathComplexCover {
                index_start: self.current_polygon_index_count.saturating_sub(count),
                index_count: count,
            },
        };

        self.batches.push((new_batch, self.current_scissor));
    }

    pub fn reset(&mut self) {
        self.batches.clear();
        self.current_circle_count = 0;
        self.current_rect_count = 0;
        self.current_line_count = 0;
        self.current_polygon_index_count = 0;
        self.current_grad_rect_count = 0;

        self.pending_circles.clear();
        self.pending_rects.clear();
        self.pending_lines.clear();
        self.pending_polygon_vertices.clear();
        self.pending_polygon_indices.clear();
        self.pending_gradient_rects.clear();
        self.pending_path_points.clear();
        self.pending_path_styles.clear();
        self.pending_path_args.clear();

        self.uploaded_circle_count = 0;
        self.uploaded_rect_count = 0;
        self.uploaded_line_count = 0;
        self.uploaded_polygon_index_count = 0;
        self.uploaded_gradient_rect_count = 0;

        self.collected_texts.clear();
    }

    // ============================================================================
    // Pipeline Creation Helpers
    // ============================================================================

    fn create_circle_pipeline(
        device: &wgpu::Device,
        shader: &wgpu::ShaderModule,
        global_layout: &wgpu::BindGroupLayout,
        instance_layout: &wgpu::BindGroupLayout,
    ) -> wgpu::RenderPipeline {
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Circle Pipeline Layout"),
            bind_group_layouts: &[Some(global_layout), Some(instance_layout)],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Circle Render Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("circle_vs"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("circle_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Always),
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState::IGNORE,
                    back: wgpu::StencilFaceState::IGNORE,
                    read_mask: 0,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }

    fn create_line_pipeline(
        device: &wgpu::Device,
        shader: &wgpu::ShaderModule,
        global_layout: &wgpu::BindGroupLayout,
        instance_layout: &wgpu::BindGroupLayout,
    ) -> wgpu::RenderPipeline {
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Line Pipeline Layout"),
            bind_group_layouts: &[Some(global_layout), Some(instance_layout)],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Line Render Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("line_vs"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("line_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Always),
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState::IGNORE,
                    back: wgpu::StencilFaceState::IGNORE,
                    read_mask: 0,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }

    fn create_rect_pipeline(
        device: &wgpu::Device,
        shader: &wgpu::ShaderModule,
        global_layout: &wgpu::BindGroupLayout,
        instance_layout: &wgpu::BindGroupLayout,
    ) -> wgpu::RenderPipeline {
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Rect Pipeline Layout"),
            bind_group_layouts: &[Some(global_layout), Some(instance_layout)],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Rect Render Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("rect_vs"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("rect_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Always),
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState::IGNORE,
                    back: wgpu::StencilFaceState::IGNORE,
                    read_mask: 0,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }

    fn create_polygon_pipeline(
        device: &wgpu::Device,
        shader: &wgpu::ShaderModule,
        global_layout: &wgpu::BindGroupLayout,
    ) -> wgpu::RenderPipeline {
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Polygon Pipeline Layout"),
            bind_group_layouts: &[Some(global_layout)],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Polygon Render Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("polygon_vs"),
                buffers: &[PathVertex::DESC],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("polygon_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            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: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Always),
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState::IGNORE,
                    back: wgpu::StencilFaceState::IGNORE,
                    read_mask: 0,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }

    fn create_gradient_rect_pipeline(
        device: &wgpu::Device,
        shader: &wgpu::ShaderModule,
        global_layout: &wgpu::BindGroupLayout,
        instance_layout: &wgpu::BindGroupLayout,
    ) -> wgpu::RenderPipeline {
        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("Gradient Rect Pipeline Layout"),
            bind_group_layouts: &[Some(global_layout), Some(instance_layout)],
            immediate_size: 0,
        });

        device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("Gradient Rect Render Pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: shader,
                entry_point: Some("grad_rect_vs"),
                buffers: &[],
                compilation_options: Default::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: shader,
                entry_point: Some("grad_rect_fs"),
                targets: &[Some(wgpu::ColorTargetState {
                    format: wgpu::TextureFormat::Rgba8Unorm,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: Default::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleStrip,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: None,
                unclipped_depth: false,
                polygon_mode: wgpu::PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: wgpu::TextureFormat::Depth24PlusStencil8,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Always),
                stencil: wgpu::StencilState {
                    front: wgpu::StencilFaceState::IGNORE,
                    back: wgpu::StencilFaceState::IGNORE,
                    read_mask: 0,
                    write_mask: 0,
                },
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        })
    }

    fn create_dummy_buffer<T: Pod>(device: &wgpu::Device) -> wgpu::Buffer {
        device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some(format!("Dummy {} Buffer", std::any::type_name::<T>()).as_str()),
            contents: bytemuck::cast_slice(&[T::zeroed()]),
            usage: wgpu::BufferUsages::STORAGE
                | wgpu::BufferUsages::COPY_DST
                | wgpu::BufferUsages::VERTEX
                | wgpu::BufferUsages::INDEX,
        })
    }

    fn create_buffer<T: Pod>(&self, data: &[T]) -> wgpu::Buffer {
        self.device
            .create_buffer_init(&wgpu::util::BufferInitDescriptor {
                label: Some(format!("Updated {} Buffer", std::any::type_name::<T>()).as_str()),
                contents: bytemuck::cast_slice(data),
                usage: wgpu::BufferUsages::STORAGE
                    | wgpu::BufferUsages::COPY_DST
                    | wgpu::BufferUsages::VERTEX
                    | wgpu::BufferUsages::INDEX,
            })
    }

    /// Renders a stroked path using GPU extrusion (simple open/closed polylines).
    fn stroke_path(&mut self, config: PathConfig) {
        if config.points.len() < 2 {
            return;
        }

        let start_point_idx = self.pending_path_points.len() as u32;
        let point_count = config.points.len() as u32;
        let style_idx = self.pending_path_styles.len() as u32;
        let path_idx = self.pending_path_args.len() as u32;

        for &(x, y) in &config.points {
            self.pending_path_points.push(GpuPathPoint { x, y });
        }

        let stroke_color = config.stroke.rgba();
        self.pending_path_styles.push(GpuPathStyle {
            r: stroke_color[0],
            g: stroke_color[1],
            b: stroke_color[2],
            a: stroke_color[3] * config.opacity,
            thickness: config.stroke_width,
            _pad0: 0.0,
            _pad1: 0.0,
            _pad2: 0.0,
        });

        self.pending_path_args.push(GpuPathArgs {
            start_point_idx,
            style_idx,
            _pad0: 0,
            _pad1: 0,
        });

        self.batches.push((
            DrawBatch::PathSimple {
                path_idx,
                point_count,
            },
            self.current_scissor,
        ));
    }

    /// Complex Path (Stencil-then-Cover universal concave polygon filler)
    fn fill_path_complex(&mut self, config: PathConfig) {
        if config.points.len() < 3 {
            return;
        }

        let point_count = config.points.len();
        let base_vertex = self.pending_polygon_vertices.len() as u16;

        // ====================================================================
        // PASS 1: STENCIL (Triangle Fan with Odd-Even Winding)
        // ====================================================================
        // Push all vertices of the complex polygon. Color is irrelevant as
        // this pass disables color writes.
        for &(x, y) in &config.points {
            self.pending_polygon_vertices.push(PathVertex {
                position: [x, y],
                color: [0.0, 0.0, 0.0, 0.0],
                is_fill: 1.0,
            });
        }

        // Generate indices using a Triangle Fan topology (anchor at the first vertex)
        let mut stencil_indices = Vec::new();
        for i in 1..point_count - 1 {
            stencil_indices.extend([
                base_vertex, // The first vertex, index 0
                base_vertex + i as u16,
                base_vertex + (i + 1) as u16,
            ]);
        }

        let stencil_index_count = stencil_indices.len() as u32;
        self.pending_polygon_indices.extend(stencil_indices);
        self.current_polygon_index_count += stencil_index_count;

        // Dispatch to the dedicated Stencil pipeline batch
        self.push_batch(BatchType::PathComplexStencil, stencil_index_count);

        // ====================================================================
        // PASS 2: COVER (Bounding Box Fill)
        // ====================================================================
        // Calculate the bounding box to minimize the GPU pixel fill area
        let mut min_x = f32::MAX;
        let mut max_x = f32::MIN;
        let mut min_y = f32::MAX;
        let mut max_y = f32::MIN;
        for &(x, y) in &config.points {
            if x < min_x {
                min_x = x;
            }
            if x > max_x {
                max_x = x;
            }
            if y < min_y {
                min_y = y;
            }
            if y > max_y {
                max_y = y;
            }
        }

        let fill = config.fill.rgba();
        let fill_color = [fill[0], fill[1], fill[2], fill[3] * config.opacity];
        let cover_base = self.pending_polygon_vertices.len() as u16;

        // Generate a quad covering the bounding box
        let bb_points = [
            (min_x, min_y),
            (max_x, min_y),
            (max_x, max_y),
            (min_x, max_y),
        ];

        for &(x, y) in &bb_points {
            self.pending_polygon_vertices.push(PathVertex {
                position: [x, y],
                color: fill_color,
                is_fill: 1.0,
            });
        }

        let cover_indices = vec![
            cover_base,
            cover_base + 1,
            cover_base + 2,
            cover_base,
            cover_base + 2,
            cover_base + 3,
        ];

        let cover_index_count = cover_indices.len() as u32;
        self.pending_polygon_indices.extend(cover_indices);
        self.current_polygon_index_count += cover_index_count;

        // Dispatch to the dedicated Cover pipeline batch (renders where stencil != 0)
        self.push_batch(BatchType::PathComplexCover, cover_index_count);
    }

    // ============================================================================
    // Render & Flush
    // ============================================================================
    pub fn flush_and_render(
        &mut self,
        view: &wgpu::TextureView, // Required to bind the hardware stencil attachment
        output_ledger: &mut Vec<TextConfig>,
    ) {
        // --------------------------------------------------------------------
        // PHASE 1: GPU DATA UPLOAD (Host-to-Device Memory Transfer)
        // --------------------------------------------------------------------
        if !self.pending_circles.is_empty() {
            let circles = std::mem::take(&mut self.pending_circles);
            self.circle_buffer = self.create_buffer(&circles);
            self.uploaded_circle_count = circles.len() as u32;
        }

        if !self.pending_rects.is_empty() {
            let rects = std::mem::take(&mut self.pending_rects);
            self.rect_buffer = self.create_buffer(&rects);
            self.uploaded_rect_count = rects.len() as u32;
        }

        if !self.pending_lines.is_empty() {
            let lines = std::mem::take(&mut self.pending_lines);
            self.line_buffer = self.create_buffer(&lines);
            self.uploaded_line_count = lines.len() as u32;
        }

        // Shared buffer allocation for both standard polygons and complex path geometry
        if !self.pending_polygon_vertices.is_empty() || !self.pending_polygon_indices.is_empty() {
            let vertices = std::mem::take(&mut self.pending_polygon_vertices);
            let indices = std::mem::take(&mut self.pending_polygon_indices);
            self.polygon_vertex_buffer = self.create_buffer(&vertices);
            self.polygon_index_buffer = self.create_buffer(&indices);
            self.uploaded_polygon_index_count = indices.len() as u32;
        }

        if !self.pending_gradient_rects.is_empty() {
            let grad_rects = std::mem::take(&mut self.pending_gradient_rects);
            self.gradient_rect_buffer = self.create_buffer(&grad_rects);
            self.uploaded_gradient_rect_count = grad_rects.len() as u32;
        }

        // Generate the structural bind group for uniform-based vector paths if data exists
        let path_bind_group = if !self.pending_path_points.is_empty() {
            let points_buf = self.create_buffer(&self.pending_path_points);
            let styles_buf = self.create_buffer(&self.pending_path_styles);
            let args_buf = self.create_buffer(&self.pending_path_args);

            Some(self.device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some("Path Bind Group 1"),
                layout: &self.path_bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: wgpu::BindingResource::Buffer(
                            points_buf.as_entire_buffer_binding(),
                        ),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: wgpu::BindingResource::Buffer(
                            styles_buf.as_entire_buffer_binding(),
                        ),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: wgpu::BindingResource::Buffer(
                            args_buf.as_entire_buffer_binding(),
                        ),
                    },
                ],
            }))
        } else {
            None
        };

        // --------------------------------------------------------------------
        // PHASE 2: BIND GROUP SETUP (Global and Instanced Storage)
        // --------------------------------------------------------------------

        self.global_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Global Bind Group 0"),
            layout: &self.global_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(
                    self.uniform_buffer.as_entire_buffer_binding(),
                ),
            }],
        });

        let circle_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Circle Instance Group 1"),
            layout: &self.instance_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(
                    self.circle_buffer.as_entire_buffer_binding(),
                ),
            }],
        });

        let rect_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Rect Instance Group 1"),
            layout: &self.instance_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(
                    self.rect_buffer.as_entire_buffer_binding(),
                ),
            }],
        });

        let line_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Line Instance Group 1"),
            layout: &self.instance_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(
                    self.line_buffer.as_entire_buffer_binding(),
                ),
            }],
        });

        let grad_rect_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Gradient Rect Instance Group 1"),
            layout: &self.instance_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::Buffer(
                    self.gradient_rect_buffer.as_entire_buffer_binding(),
                ),
            }],
        });

        // Main descriptor incorporating the mandatory stencil target attachment
        let render_pass_desc = wgpu::RenderPassDescriptor {
            label: Some("Main Render Pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view,
                resolve_target: None,
                ops: wgpu::Operations {
                    load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                    store: wgpu::StoreOp::Store,
                },
                depth_slice: None,
            })],
            // Binds depth_stencil and clears the stencil buffer to 0 at the start of the frame
            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                view: &self.depth_stencil_view,
                depth_ops: None,
                stencil_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(0),
                    store: wgpu::StoreOp::Store,
                }),
            }),
            occlusion_query_set: None,
            timestamp_writes: None,
            multiview_mask: None,
        };

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Render Encoder"),
            });

        // --------------------------------------------------------------------
        // PHASE 3: ORCHESTRATED DRAWING (Multi-Group Context Switching)
        // --------------------------------------------------------------------
        {
            let mut pass = encoder.begin_render_pass(&render_pass_desc);

            // Bind global environment once for the entire pass
            pass.set_bind_group(0, &self.global_bind_group, &[]);

            // Tracks the current scissor state on the GPU to minimize redundant commands
            let mut active_scissor: Option<(u32, u32, u32, u32)> = None;

            for (batch, scissor) in &self.batches {
                // Dynamically update GPU hardware scissor rect if the domain changed
                if *scissor != active_scissor {
                    if let Some((x, y, w, h)) = scissor {
                        pass.set_scissor_rect(*x, *y, *w, *h);
                    } else {
                        // Restore to full-screen viewport when no clipping is active
                        pass.set_scissor_rect(0, 0, self.physical_width, self.physical_height);
                    }
                    active_scissor = *scissor;
                }

                match batch {
                    DrawBatch::Circle { start, count } => {
                        pass.set_pipeline(&self.circle_pipeline);
                        pass.set_bind_group(1, &circle_bind_group, &[]);
                        pass.draw(0..4, *start..(*start + *count));
                    }
                    DrawBatch::Rect { start, count } => {
                        pass.set_pipeline(&self.rect_pipeline);
                        pass.set_bind_group(1, &rect_bind_group, &[]);
                        pass.draw(0..4, *start..(*start + *count));
                    }
                    DrawBatch::Line { start, count } => {
                        pass.set_pipeline(&self.line_pipeline);
                        pass.set_bind_group(1, &line_bind_group, &[]);
                        pass.draw(0..4, *start..(*start + *count));
                    }
                    DrawBatch::GradientRect { start, count } => {
                        pass.set_pipeline(&self.gradient_rect_pipeline);
                        pass.set_bind_group(1, &grad_rect_bind_group, &[]);
                        pass.draw(0..4, *start..(*start + *count));
                    }
                    DrawBatch::Polygon {
                        index_start,
                        index_count,
                    } => {
                        pass.set_pipeline(&self.polygon_pipeline);
                        // Polygon does not rely on Group 1 instance storage
                        pass.set_vertex_buffer(0, self.polygon_vertex_buffer.slice(..));
                        pass.set_index_buffer(
                            self.polygon_index_buffer.slice(..),
                            wgpu::IndexFormat::Uint16,
                        );
                        pass.draw_indexed(*index_start..(*index_start + *index_count), 0, 0..1);
                    }
                    DrawBatch::PathSimple {
                        path_idx,
                        point_count,
                    } => {
                        if let Some(global_path_bg) = &path_bind_group {
                            pass.set_pipeline(&self.path_simple_pipeline);
                            pass.set_bind_group(1, global_path_bg, &[]);

                            let virtual_vertex_count = (*point_count - 1) * 6;
                            pass.draw(0..virtual_vertex_count, *path_idx..(*path_idx + 1));
                        }
                    }
                    // COMPONENT 1: Stencil Pass - Carves the winding topology into the stencil target
                    DrawBatch::PathComplexStencil {
                        index_start,
                        index_count,
                    } => {
                        pass.set_pipeline(&self.complex_stencil_pipeline);
                        pass.set_vertex_buffer(0, self.polygon_vertex_buffer.slice(..));
                        pass.set_index_buffer(
                            self.polygon_index_buffer.slice(..),
                            wgpu::IndexFormat::Uint16,
                        );
                        pass.set_stencil_reference(0); // Sets baseline comparison reference
                        pass.draw_indexed(*index_start..(*index_start + *index_count), 0, 0..1);
                    }
                    // COMPONENT 2: Cover Pass - Fills pixels matching the mask, resetting the stencil to 0 inline
                    DrawBatch::PathComplexCover {
                        index_start,
                        index_count,
                    } => {
                        pass.set_pipeline(&self.complex_cover_pipeline);
                        pass.set_vertex_buffer(0, self.polygon_vertex_buffer.slice(..));
                        pass.set_index_buffer(
                            self.polygon_index_buffer.slice(..),
                            wgpu::IndexFormat::Uint16,
                        );
                        pass.set_stencil_reference(0);
                        pass.draw_indexed(*index_start..(*index_start + *index_count), 0, 0..1);
                    }
                }
            }
        }

        // Submit operational command buffer stream to the GPU graphics queue
        self.queue.submit(Some(encoder.finish()));

        // Offload UI text configurations for external composition passes
        output_ledger.clear();
        output_ledger.append(&mut self.collected_texts);

        // Reset temporary buffers and batch lists for the next rendering cycle
        self.reset();
    }
}

// ============================================================================
// RenderBackend Trait Implementation
// ============================================================================

impl RenderBackend for WgpuBackend {
    fn begin_clip_scope(&mut self, rect: &crate::coordinate::Rect) {
        // Convert virtual logical coordinates into physical pixels
        let physical_x = ((rect.x as f32) * self.scale_factor).max(0.0) as u32;
        let physical_y = ((rect.y as f32) * self.scale_factor).max(0.0) as u32;
        let physical_w = ((rect.width as f32) * self.scale_factor).max(1.0) as u32;
        let physical_h = ((rect.height as f32) * self.scale_factor).max(1.0) as u32;

        // Clamp tightly to the safe physical boundaries to prevent WGPU panic/crashes
        let x = physical_x.min(self.physical_width);
        let y = physical_y.min(self.physical_height);
        let w = physical_w.min(self.physical_width.saturating_sub(x)).max(1);
        let h = physical_h
            .min(self.physical_height.saturating_sub(y))
            .max(1);

        self.current_scissor = Some((x, y, w, h));
    }

    fn end_clip_scope(&mut self) {
        // Reset the state to full viewport rendering
        self.current_scissor = None;
    }

    fn draw_circle(&mut self, config: CircleConfig) {
        let fill = config.fill.rgba();
        let stroke = config.stroke.rgba();

        let point = GpuPoint {
            x: config.x,
            y: config.y,
            fill_r: fill[0],
            fill_g: fill[1],
            fill_b: fill[2],
            fill_a: fill[3] * config.opacity,
            stroke_r: stroke[0],
            stroke_g: stroke[1],
            stroke_b: stroke[2],
            stroke_a: stroke[3],
            radius: config.radius,
            stroke_width: config.stroke_width,
        };

        self.pending_circles.push(point);
        self.current_circle_count += 1;
        self.push_batch(BatchType::Circle, 1);
    }

    fn draw_rect(&mut self, config: RectConfig) {
        let fill = config.fill.rgba();
        let stroke = config.stroke.rgba();

        let rect = GpuRect {
            x: config.x,
            y: config.y,
            width: config.width,
            height: config.height,
            fill_r: fill[0],
            fill_g: fill[1],
            fill_b: fill[2],
            fill_a: fill[3] * config.opacity,
            stroke_r: stroke[0],
            stroke_g: stroke[1],
            stroke_b: stroke[2],
            stroke_a: stroke[3],
            stroke_width: config.stroke_width,
            corner_radius: 0.0,
        };

        self.pending_rects.push(rect);
        self.current_rect_count += 1;
        self.push_batch(BatchType::Rect, 1);
    }

    fn draw_line(&mut self, config: LineConfig) {
        let color = config.color.rgba();
        let line = GpuLine {
            x1: config.x1,
            y1: config.y1,
            x2: config.x2,
            y2: config.y2,
            r: color[0],
            g: color[1],
            b: color[2],
            a: color[3] * config.opacity,
            width: config.width,
            _pad1: 0.0,
            _pad2: 0.0,
            _pad3: 0.0,
        };

        self.pending_lines.push(line);
        self.current_line_count += 1;
        self.push_batch(BatchType::Line, 1);
    }

    /// Draws a fully enclosed polygon primitive by sequentially generating its interior fill mesh and boundary stroke.
    fn draw_polygon(&mut self, config: PolygonConfig) {
        // A valid polygon requires at least 3 vertices to form an enclosed area
        if config.points.len() < 3 {
            return;
        }

        // ====================================================================
        // LAYER 1: Fill Phase - Tessellation via Triangle Fan
        // ====================================================================
        // Only process fill geometry if the alpha channel is greater than zero
        if config.fill.rgba()[3] > 0.0 {
            let fill = config.fill.rgba();
            // Premultiply the layer's global opacity with the fill color's alpha channel
            let color = [fill[0], fill[1], fill[2], fill[3] * config.opacity];

            // Record the starting index in the vertex buffer to calculate local index offsets
            let base_vertex = self.pending_polygon_vertices.len() as u16;
            let point_count = config.points.len();

            // Push polygon coordinates into the vertex buffer
            for &(x, y) in &config.points {
                self.pending_polygon_vertices.push(PathVertex {
                    position: [x, y],
                    color,
                    is_fill: 1.0, // Flag indicating this vertex belongs to a fill mesh
                });
            }

            // Generate Index Buffer using a Triangle Fan topology (suitable for convex polygons)
            let mut indices = Vec::new();
            for i in 1..point_count - 1 {
                indices.extend([
                    base_vertex,
                    base_vertex + i as u16,
                    base_vertex + (i + 1) as u16,
                ]);
            }

            let index_count = indices.len() as u32;
            self.pending_polygon_indices.extend(indices);
            self.current_polygon_index_count += index_count;

            // Dispatch a draw batch for the fill geometry
            self.push_batch(BatchType::Polygon, index_count);
        }

        // ====================================================================
        // LAYER 2: Stroke Phase & Auto-AA Fringe Generation
        // ====================================================================
        // Evaluate geometric rendering requirements based on style attributes
        let has_stroke = config.stroke_width > 0.0 && config.stroke.rgba()[3] > 0.0;
        let has_fill = config.fill.rgba()[3] > 0.0;

        // An edge pass is required if a custom stroke is defined, or if a fill
        // exists and needs an anti-aliasing perimeter to prevent stencil aliasing (jagged edges).
        if has_stroke || has_fill {
            let mut closed_points = config.points.clone();

            // The underlying path extrusion pipeline processes inputs as open
            // polylines. To render a proper closed polygon loop, we duplicate and append the
            // first vertex to the end of the collection, forcing the final segment to tie back to the start.
            if let Some(&first_pt) = config.points.first() {
                closed_points.push(first_pt);
            }

            if has_stroke {
                // Scenario A: Standard User-Defined Stroke
                // Dispatches a dedicated wireframe mesh generation pass using the assigned stroke configuration.
                self.stroke_path(PathConfig {
                    points: closed_points,
                    fill: crate::visual::color::SingleColor::none(), // Prevent redundant stencil operations
                    stroke: config.stroke,
                    stroke_width: config.stroke_width,
                    opacity: config.opacity,
                    dash: vec![], // Polygons implicitly utilize solid stroke patterns
                    topology: PathTopology::Simple,
                });
            } else {
                // Scenario B: Auto-AA Fringe (Automatic Edge Feathering)
                // When a polygon has a solid fill but no outline, the standard binary stencil-then-cover
                // rasterization leaves hard, jagged pixels.
                //
                // THE TRICK: We injected a ghost stroke with a physical width of 0.0, matching the fill color.
                // Guided by the shader's internal 1.5px screen-space padding and SDF-driven alpha-stepping,
                // this generates a sub-pixel anti-aliasing gradient that perfectly smooths out the raw mesh boundaries.
                self.stroke_path(PathConfig {
                    points: closed_points,
                    fill: crate::visual::color::SingleColor::none(),
                    stroke: config.fill, // Fallback to fill color for seamless edge integration
                    stroke_width: 0.0, // Zero physical width; relies entirely on the shader's AA padding
                    opacity: config.opacity,
                    dash: vec![],
                    topology: PathTopology::Simple,
                });
            }
        }
    }

    fn draw_gradient_rect(&mut self, config: GradientRectConfig) {
        if config.stops.is_empty() {
            return;
        }

        if config.stops.len() == 1 {
            let start_rgba = config.stops[0].1.rgba();
            let grad_rect = GpuGradientRect {
                x: config.x,
                y: config.y,
                width: config.width,
                height: config.height,
                start_r: start_rgba[0],
                start_g: start_rgba[1],
                start_b: start_rgba[2],
                start_a: start_rgba[3],
                end_r: start_rgba[0],
                end_g: start_rgba[1],
                end_b: start_rgba[2],
                end_a: start_rgba[3],
                angle: 0.0,
                opacity: 1.0,
            };
            self.pending_gradient_rects.push(grad_rect);
            self.current_grad_rect_count += 1;
            self.push_batch(BatchType::GradientRect, 1);
            return;
        }

        let mut count = 0;
        for window in config.stops.windows(2) {
            let (offset1, color1) = &window[0];
            let (offset2, color2) = &window[1];

            let (sub_x, sub_y, sub_width, sub_height) = if config.is_vertical {
                (
                    config.x,
                    config.y + offset1 * config.height,
                    config.width,
                    (offset2 - offset1) * config.height,
                )
            } else {
                (
                    config.x + offset1 * config.width,
                    config.y,
                    (offset2 - offset1) * config.width,
                    config.height,
                )
            };

            let start_rgba = color1.rgba();
            let end_rgba = color2.rgba();

            let grad_rect = GpuGradientRect {
                x: sub_x,
                y: sub_y,
                width: sub_width,
                height: sub_height,
                start_r: start_rgba[0],
                start_g: start_rgba[1],
                start_b: start_rgba[2],
                start_a: start_rgba[3],
                end_r: end_rgba[0],
                end_g: end_rgba[1],
                end_b: end_rgba[2],
                end_a: end_rgba[3],
                angle: if config.is_vertical {
                    std::f32::consts::FRAC_PI_2
                } else {
                    0.0
                },
                opacity: 1.0,
            };

            self.pending_gradient_rects.push(grad_rect);
            count += 1;
        }

        self.current_grad_rect_count += count;
        self.push_batch(BatchType::GradientRect, count);
    }

    /// Routes the incoming vector path configuration by decomposing it into
    /// two highly optimized, complementary GPU execution phases.
    fn draw_path(&mut self, config: PathConfig) {
        // PHASE 1: Interior Geometry Rasterization (No Edges)
        let has_fill = config.fill.rgba()[3] > 0.0 && config.opacity > 0.0;
        if has_fill {
            self.fill_path_complex(config.clone());
        }

        // PHASE 2: Boundary Wireframe Mesh Generation (No Fills)
        let has_stroke = config.stroke_width > 0.0 && config.stroke.rgba()[3] > 0.0;
        if has_stroke {
            self.stroke_path(config);
        } else if has_fill {
            // Auto anti-aliasing fringe
            let mut aa_config = config.clone();
            aa_config.stroke = config.fill;
            aa_config.stroke_width = 0.0; // Make the edge smooth while keeping the fill color
            self.stroke_path(aa_config);
        }
    }

    fn draw_text(&mut self, config: TextConfig) {
        self.collected_texts.push(config);
    }
}