1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
use super::*;
/// Packing, conversion, and compile-time ABI stride verification helpers for `GpuPrimitiveInstance`.
impl GpuPrimitiveInstance {
/// Packs normalized `[r, g, b, a]` floating-point channels into little-endian RGBA8 `u32`.
///
/// # Arguments
///
/// - `[f32; 4]` - Normalized RGBA channels in `[0.0..=1.0]`.
///
/// # Returns
///
/// - `u32` - Packed RGBA8 color word (`R` in low byte, `A` in high byte).
#[must_use]
pub fn pack_rgba8_f32(rgba: [f32; 4]) -> u32 {
let red_val: u32 = (rgba[0].clamp(0.0, 1.0) * 255.0).round() as u32;
let green_val: u32 = (rgba[1].clamp(0.0, 1.0) * 255.0).round() as u32;
let blue_val: u32 = (rgba[2].clamp(0.0, 1.0) * 255.0).round() as u32;
let alpha_val: u32 = (rgba[3].clamp(0.0, 1.0) * 255.0).round() as u32;
red_val | (green_val << 8) | (blue_val << 16) | (alpha_val << 24)
}
/// Packs a `Color` into little-endian RGBA8 `u32`.
///
/// # Arguments
///
/// - `Color` - Source sRGB color with alpha.
///
/// # Returns
///
/// - `u32` - Packed RGBA8 color word.
#[must_use]
pub fn pack_color_rgba8(color: Color) -> u32 {
(color.get_red() as u32)
| ((color.get_green() as u32) << 8)
| ((color.get_blue() as u32) << 16)
| ((color.get_alpha() as u32) << 24)
}
/// Packs a non-negative physical pixel radius into Q12.4 unsigned fixed-point (`1/16` px).
///
/// # Arguments
///
/// - `f32` - Physical pixel measurement (`>= 0.0`).
///
/// # Returns
///
/// - `u16` - Q12.4 quantized fixed-point value.
#[must_use]
pub fn pack_u16_q4(value: f32) -> u16 {
(value.clamp(0.0, 4095.9375) * 16.0).round() as u16
}
/// Returns the geometric corner-radius ceiling (half the shortest side) for a quad so oversized
/// full-pill radii (e.g. `999.0` logical px at high DPR) encode losslessly within Q12.4 range.
///
/// # Arguments
///
/// - `[f32; 4]` - Physical quad rectangle `[x, y, w, h]` (shadow quads include blur padding).
/// - `u32` - Primitive kind discriminant (`2` = shadow).
/// - `f32` - Shadow blur padding stored in the angle slot for shadow quads.
///
/// # Returns
///
/// - `f32` - Maximum meaningful corner radius in physical pixels.
#[must_use]
pub fn corner_radius_cap(rect: [f32; 4], kind: u32, shadow_pad: f32) -> f32 {
let shortest: f32 = rect[2].min(rect[3]);
let inner: f32 = if kind == GpuPrimitiveKind::Shadow as u32 {
shortest - shadow_pad * 2.0
} else {
shortest
};
(inner * 0.5).max(0.0)
}
/// Converts a finite `f32` into IEEE-754 binary16 (`f16`) raw bit representation.
///
/// # Arguments
///
/// - `f32` - Single-precision floating-point value.
///
/// # Returns
///
/// - `u16` - IEEE-754 binary16 encoded bits.
#[must_use]
pub fn f32_to_f16_bits(value: f32) -> u16 {
let bits: u32 = value.to_bits();
let sign: u32 = (bits >> 16) & 0x8000;
let exp: i32 = ((bits >> 23) & 0xFF) as i32 - 127 + 15;
let frac: u32 = bits & 0x007F_FFFF;
if exp <= 0 {
if exp < -10 {
return sign as u16;
}
let mant: u32 = (frac | 0x0080_0000) >> (1 - exp);
return (sign | ((mant + 0x1000) >> 13)) as u16;
}
if exp >= 31 {
return (sign | 0x7C00) as u16;
}
let rounded: u32 = frac + 0x1000;
if (rounded & 0x0080_0000) != 0 {
(sign | (((exp + 1) as u32) << 10)) as u16
} else {
(sign | ((exp as u32) << 10) | (rounded >> 13)) as u16
}
}
/// Packs two `f32` values into an IEEE-754 `f16x2` `u32` matching GPU `unpack2x16float` / `half2`.
///
/// # Arguments
///
/// - `f32` - Low-lane parameter (`stroke_or_blur`).
/// - `f32` - High-lane parameter (`angle_or_pad`).
///
/// # Returns
///
/// - `u32` - Packed `f16x2` parameter word.
#[must_use]
pub fn pack_f16x2(lo: f32, hi: f32) -> u32 {
(Self::f32_to_f16_bits(lo) as u32) | ((Self::f32_to_f16_bits(hi) as u32) << 16)
}
/// Encodes `PrimKind`, `clip_mask_or_sub`, `tex_slot`, and `layer_id` into `kind_flags`.
///
/// # Arguments
///
/// - `PrimKind` - Unified 8-variant primitive discriminant (`bits[0..4]`).
/// - `u16` - Clip-mask identifier or `VectorSubKind` (`bits[4..16]`).
/// - `u8` - Bound texture slot index (`bits[16..24]`).
/// - `u8` - Owning retained layer identifier (`bits[24..32]`).
///
/// # Returns
///
/// - `u32` - Packed `kind_flags` bitfield.
#[must_use]
pub const fn pack_kind_flags(
kind: PrimKind,
clip_mask_or_sub: u16,
tex_slot: u8,
layer_id: u8,
) -> u32 {
((kind as u32) & 0xF)
| (((clip_mask_or_sub as u32) & 0xFFF) << 4)
| ((tex_slot as u32) << 16)
| ((layer_id as u32) << 24)
}
/// Decodes the `PrimKind` variant stored in `kind_flags` bits `[0..4]`.
///
/// # Returns
///
/// - `PrimKind` - Decoded primitive variant.
#[must_use]
pub fn prim_kind(&self) -> PrimKind {
match self.get_kind_flags() & 0xF {
1 => PrimKind::LinearGradientRect,
2 => PrimKind::Shadow,
3 => PrimKind::GlyphAlpha8,
4 => PrimKind::GlyphColorRgba8,
5 => PrimKind::ImageTexture,
6 => PrimKind::VectorShape,
7 => PrimKind::ExternalGpuSurface,
8 => PrimKind::BackdropBlur,
_ => PrimKind::RoundedRect,
}
}
/// Returns the `clip_mask_id` / `VectorSubKind` stored in `kind_flags` bits `[4..16]`.
///
/// # Returns
///
/// - `u16` - Encoded clip-mask ID or vector sub-kind.
#[must_use]
pub fn clip_or_sub_kind(&self) -> u16 {
((self.get_kind_flags() >> 4) & 0xFFF) as u16
}
/// Encodes a physical rounded-clip corner radius (`0.0..=500.0 px`) into 6 bits matching all 4 uber-shaders.
///
/// # Arguments
///
/// - `f32` - Physical rounded-clip radius in pixels.
///
/// # Returns
///
/// - `u16` - Quantized 6-bit value in `0..=63`.
#[must_use]
pub fn encode_clip_radius_6bit(radius_px: f32) -> u16 {
let clamped: f32 = radius_px.clamp(0.0, 500.0);
if clamped <= 15.5 {
(clamped * 2.0).round().clamp(0.0, 31.0) as u16
} else if clamped <= 76.0 {
32_u16 + (((clamped - 16.0) / 4.0).round().clamp(0.0, 15.0) as u16)
} else {
48_u16 + (((clamped - 80.0) / 28.0).round().clamp(0.0, 15.0) as u16)
}
}
/// Decodes a 6-bit rounded-clip radius code back to physical pixels matching all 4 uber-shaders.
///
/// # Arguments
///
/// - `u16` - Quantized 6-bit radius code in `0..=63`.
///
/// # Returns
///
/// - `f32` - Decoded physical rounded-clip radius in pixels.
#[must_use]
pub fn decode_clip_radius_6bit(encoded: u16) -> f32 {
let masked: u16 = encoded & 0x3F;
if masked <= 31 {
(masked as f32) * 0.5
} else if masked <= 47 {
16.0 + ((masked - 32) as f32) * 4.0
} else {
80.0 + ((masked - 48) as f32) * 28.0
}
}
/// Encodes a 10-bit per-corner rounded-clip descriptor (`bits[0..4]` = active `TL/TR/BR/BL` corner mask, `bits[4..10]` = extended 6-bit physical radius up to `500px`) across nested rectangular and rounded clips.
///
/// # Arguments
///
/// - `Rect` - Parent active physical scissor rectangle.
/// - `u16` - Parent encoded 10-bit rounded-clip descriptor.
/// - `Rect` - Intersected child physical scissor rectangle.
/// - `Rect` - Newly pushed physical clip rectangle.
/// - `Option<CornerRadius>` - Newly pushed physical corner radii (`None` for rectangular `PushClip`).
///
/// # Returns
///
/// - `u16` - Encoded 10-bit rounded-clip descriptor (`0` when no rounded corner touches `next_scissor`).
#[must_use]
pub fn encode_rounded_clip_bits(
parent_scissor: Rect,
parent_bits: u16,
next_scissor: Rect,
pushed_rect: Rect,
pushed_radius_phys: Option<CornerRadius>,
) -> u16 {
if next_scissor.get_width() <= 0.0 || next_scissor.get_height() <= 0.0 {
return 0;
}
let parent_mask: u16 = parent_bits & 0xF;
let parent_q_rad: u16 = (parent_bits >> 4) & 0x3F;
let mut mask: u16 = 0;
if parent_mask != 0 && parent_q_rad > 0 {
let same_left: bool = (next_scissor.get_x() - parent_scissor.get_x()).abs() <= 0.5;
let same_top: bool = (next_scissor.get_y() - parent_scissor.get_y()).abs() <= 0.5;
let same_right: bool = (next_scissor.right() - parent_scissor.right()).abs() <= 0.5;
let same_bottom: bool = (next_scissor.bottom() - parent_scissor.bottom()).abs() <= 0.5;
if (parent_mask & 1) != 0 && same_left && same_top {
mask |= 1;
}
if (parent_mask & 2) != 0 && same_right && same_top {
mask |= 2;
}
if (parent_mask & 4) != 0 && same_right && same_bottom {
mask |= 4;
}
if (parent_mask & 8) != 0 && same_left && same_bottom {
mask |= 8;
}
}
let mut q_rad: u16 = if mask != 0 { parent_q_rad } else { 0 };
if let Some(rad) = pushed_radius_phys {
let cap_r: f32 = (pushed_rect.get_width() * 0.5)
.min(pushed_rect.get_height() * 0.5)
.max(0.0);
let r_tl: f32 = rad.get_top_left().min(cap_r);
let r_tr: f32 = rad.get_top_right().min(cap_r);
let r_br: f32 = rad.get_bottom_right().min(cap_r);
let r_bl: f32 = rad.get_bottom_left().min(cap_r);
let max_pushed_r: f32 = r_tl.max(r_tr).max(r_br).max(r_bl);
let pushed_q_rad: u16 = Self::encode_clip_radius_6bit(max_pushed_r);
if pushed_q_rad > 0 {
let touch_left: bool = (next_scissor.get_x() - pushed_rect.get_x()).abs() <= 0.5;
let touch_top: bool = (next_scissor.get_y() - pushed_rect.get_y()).abs() <= 0.5;
let touch_right: bool = (next_scissor.right() - pushed_rect.right()).abs() <= 0.5;
let touch_bottom: bool =
(next_scissor.bottom() - pushed_rect.bottom()).abs() <= 0.5;
let mut pushed_mask: u16 = 0;
if r_tl > 0.25 && touch_left && touch_top {
pushed_mask |= 1;
}
if r_tr > 0.25 && touch_right && touch_top {
pushed_mask |= 2;
}
if r_br > 0.25 && touch_right && touch_bottom {
pushed_mask |= 4;
}
if r_bl > 0.25 && touch_left && touch_bottom {
pushed_mask |= 8;
}
if pushed_mask != 0 {
mask |= pushed_mask;
q_rad = q_rad.max(pushed_q_rad);
}
}
}
if mask == 0 || q_rad == 0 {
0
} else {
(mask & 0xF) | ((q_rad & 0x3F) << 4)
}
}
/// Attaches a 10-bit rounded-clip descriptor into `kind_flags` bits `[6..16]`, preserving `PrimKind` (`bits[0..4]`) and `VectorSubKind` (`bits[4..6]`).
///
/// # Arguments
///
/// - `Self` - Source primitive instance.
/// - `u16` - Encoded 10-bit rounded-clip descriptor.
///
/// # Returns
///
/// - `Self` - Updated primitive instance.
#[inline(always)]
#[must_use]
pub fn with_rounded_clip_bits(mut self, rounded_clip_bits: u16) -> Self {
if rounded_clip_bits != 0 {
let current_flags: u32 = self.get_kind_flags();
let next_flags: u32 =
(current_flags & !(0x3FF_u32 << 6)) | (((rounded_clip_bits as u32) & 0x3FF) << 6);
let _: &mut Self = self.set_kind_flags(next_flags);
}
self
}
/// Returns the texture slot index stored in `kind_flags` bits `[16..24]`.
///
/// # Returns
///
/// - `u8` - Bound texture slot.
#[must_use]
pub fn texture_slot(&self) -> u8 {
((self.get_kind_flags() >> 16) & 0xFF) as u8
}
/// Returns the retained layer identifier stored in `kind_flags` bits `[24..32]`.
///
/// # Returns
///
/// - `u8` - Owning layer identifier.
#[must_use]
pub fn layer_id(&self) -> u8 {
((self.get_kind_flags() >> 24) & 0xFF) as u8
}
/// Compiles a 64-byte `GpuPrimitiveInstance` from a legacy 96-byte `GpuQuadInstance`.
///
/// # Arguments
///
/// - `&GpuQuadInstance` - Source quad descriptor.
/// - `u8` - Active texture slot index.
/// - `u8` - Active retained layer identifier.
///
/// # Returns
///
/// - `Self` - Tightly packed 64-byte GPU primitive instance.
#[must_use]
pub fn from_quad_instance(quad: &GpuQuadInstance, tex_slot: u8, layer_id: u8) -> Self {
const {
assert!(size_of::<GpuPrimitiveInstance>() == GPU_PRIMITIVE_INSTANCE_BYTES);
}
let rect: [f32; 4] = quad.get_rect();
let clip_rect: [f32; 4] = quad.get_clip();
let color_rgba: u32 = Self::pack_rgba8_f32(quad.get_color());
let mut aux_color_rgba: u32 = Self::pack_rgba8_f32(quad.get_secondary_color());
let mut uv_rect: [u16; 4] = [0, 0, u16::MAX, u16::MAX];
let src_radii: [f32; 4] = quad.get_radii();
let radius_cap: f32 = Self::corner_radius_cap(rect, quad.get_kind(), quad.get_angle_rad());
let mut radii_border: [u16; 4] = [
Self::pack_u16_q4(src_radii[0].min(radius_cap)),
Self::pack_u16_q4(src_radii[1].min(radius_cap)),
Self::pack_u16_q4(src_radii[2].min(radius_cap)),
Self::pack_u16_q4(src_radii[3].min(radius_cap)),
];
let (prim_kind, sub_kind): (PrimKind, u16) = match quad.get_kind() {
1 => (PrimKind::LinearGradientRect, 0),
2 => (PrimKind::Shadow, 0),
3 => {
let is_color_glyph: bool = (quad.get_reserved() & 0x8000_0000) != 0;
if is_color_glyph {
(PrimKind::GlyphColorRgba8, 0)
} else {
(PrimKind::GlyphAlpha8, 0)
}
}
4 => (PrimKind::ImageTexture, 0),
5 => (PrimKind::VectorShape, VectorSubKind::Circle as u16),
6 => {
let inv_w: f32 = 1.0 / rect[2].max(1.0);
let inv_h: f32 = 1.0 / rect[3].max(1.0);
let red_val: [f32; 4] = quad.get_radii();
uv_rect = [
(((red_val[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
(((red_val[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
(((red_val[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
(((red_val[3] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
];
radii_border = [0; 4];
(PrimKind::VectorShape, VectorSubKind::Line as u16)
}
7 => {
let inv_w: f32 = 1.0 / rect[2].max(1.0);
let inv_h: f32 = 1.0 / rect[3].max(1.0);
let p0: [f32; 4] = quad.get_secondary_color();
let radius_val: [f32; 4] = quad.get_radii();
let p0_nx: f32 = ((p0[0] - rect[0]) * inv_w).clamp(0.0, 1.0);
let p0_ny: f32 = ((p0[1] - rect[1]) * inv_h).clamp(0.0, 1.0);
aux_color_rgba = Self::pack_rgba8_f32([p0_nx, p0_ny, 0.0, 1.0]);
uv_rect = [
(((radius_val[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
(((radius_val[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
(((radius_val[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
(((radius_val[3] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
];
radii_border = [
(p0_nx * 65535.0).round() as u16,
(p0_ny * 65535.0).round() as u16,
0,
0,
];
(PrimKind::VectorShape, VectorSubKind::Triangle as u16)
}
8 => (PrimKind::BackdropBlur, 0),
9 => (PrimKind::ExternalGpuSurface, 0),
_ => (PrimKind::RoundedRect, 0),
};
let kind_flags: u32 = Self::pack_kind_flags(prim_kind, sub_kind, tex_slot, layer_id);
let extra_param: u32 = Self::pack_f16x2(quad.get_stroke_or_blur(), quad.get_angle_rad());
Self {
rect,
clip_rect,
color_rgba,
aux_color_rgba,
uv_rect,
radii_border,
kind_flags,
extra_param,
}
}
/// Constructs a 64-byte `PrimKind::ExternalGpuSurface` instance for shared-device 3D game or video textures.
///
/// # Arguments
///
/// - `Rect` - Destination physical bounds.
/// - `Rect` - Active physical scissor clip rectangle.
/// - `[f32; 4]` - Per-corner physical clip radii `[tl, tr, br, bl]`.
/// - `[u16; 4]` - Normalized texture UV rectangle `[u0, v0, u1, v1]`.
/// - `u8` - External GPU texture slot.
/// - `u8` - Retained layer identifier.
///
/// # Returns
///
/// - `Self` - Packed 64-byte external GPU surface primitive instance.
#[must_use]
pub fn external_surface(
bounds: Rect,
clip: Rect,
radii: [f32; 4],
uv_rect: [u16; 4],
tex_slot: u8,
layer_id: u8,
) -> Self {
Self {
rect: [
bounds.get_x(),
bounds.get_y(),
bounds.get_width(),
bounds.get_height(),
],
clip_rect: [clip.get_x(), clip.get_y(), clip.right(), clip.bottom()],
color_rgba: 0xFFFF_FFFF,
aux_color_rgba: 0,
uv_rect,
radii_border: [
Self::pack_u16_q4(radii[0]),
Self::pack_u16_q4(radii[1]),
Self::pack_u16_q4(radii[2]),
Self::pack_u16_q4(radii[3]),
],
kind_flags: Self::pack_kind_flags(PrimKind::ExternalGpuSurface, 0, tex_slot, layer_id),
extra_param: 0,
}
}
}
/// Construction helper for `GpuLayerUniform`.
impl GpuLayerUniform {
/// Creates a 16-byte layer uniform carrying physical viewport dimensions and scroll translation.
///
/// # Arguments
///
/// - `f32` - Physical viewport width in pixels.
/// - `f32` - Physical viewport height in pixels.
/// - `[f32; 2]` - Retained layer scroll offset `[scroll_x, scroll_y]` in physical pixels.
///
/// # Returns
///
/// - `Self` - Packed 16-byte GPU layer uniform.
#[must_use]
pub fn new(viewport_w: f32, viewport_h: f32, scroll_offset: [f32; 2]) -> Self {
const {
assert!(size_of::<GpuLayerUniform>() == GPU_LAYER_UNIFORM_BYTES);
}
Self {
viewport_size: [viewport_w.max(1.0), viewport_h.max(1.0)],
scroll_offset,
}
}
}
/// `GpuDriver` implementation for `RecordingGpuDriver`.
impl GpuDriver for RecordingGpuDriver {
/// Returns the configured backend tag.
///
/// # Arguments
///
/// - `&Self` - Driver reference.
///
/// # Returns
///
/// - `GraphicsBackend` - Active backend tag.
fn backend(&self) -> GraphicsBackend {
self.get_backend_kind()
}
/// Selects the canonical native shader source for this backend.
///
/// # Arguments
///
/// - `&Self` - Driver reference.
///
/// # Returns
///
/// - `&'static str` - Native shader source string.
fn shader_source(&self) -> &'static str {
match self.get_backend_kind() {
GraphicsBackend::Metal => MSL_UI_SHADER,
GraphicsBackend::Direct3D12 | GraphicsBackend::Direct3D11 => HLSL_UI_SHADER,
GraphicsBackend::WebGl2 | GraphicsBackend::OpenGlEs => GLSL_ES3_UI_FRAGMENT_SHADER,
GraphicsBackend::WebGpu
| GraphicsBackend::Vulkan
| GraphicsBackend::SoftwareCpu
| GraphicsBackend::Canvas2d
| GraphicsBackend::Headless => WGSL_UI_SHADER,
}
}
/// Records submitted GPU batches and returns draw-call count.
///
/// # Arguments
///
/// - `&Self` - Mutable driver.
/// - `u32` - Surface width.
/// - `u32` - Surface height.
/// - `Color` - Clear color.
/// - `&[GpuBatch]` - Ordered batches.
///
/// # Returns
///
/// - `Result<usize, PlatformError>` - Submitted batch count.
fn submit_batches(
&mut self,
_width: u32,
_height: u32,
clear_color: Color,
batches: &[GpuBatch],
) -> Result<usize, PlatformError> {
let count: usize = batches.len();
let instances: usize = batches
.iter()
.fold(0_usize, |acc: usize, blue_val: &GpuBatch| {
acc + blue_val
.get_primitives()
.len()
.max(blue_val.get_instances().len())
});
self.set_last_clear(clear_color);
self.set_last_instance_count(instances);
self.set_total_draw_calls(self.get_total_draw_calls().saturating_add(count));
Ok(count)
}
}
/// Instanced batch builder, order-preserving coalescer, and telemetry methods for `HardwareRenderer`.
impl HardwareRenderer {
/// Creates a hardware renderer bound to `backend` with optional deterministic pixel readback.
///
/// # Arguments
///
/// - `GraphicsBackend` - Selected GPU backend.
/// - `u32` - Initial physical width.
/// - `u32` - Initial physical height.
/// - `RenderConfig` - Rendering configuration.
/// - `bool` - Whether software readback mirror is enabled.
///
/// # Returns
///
/// - `Self` - Configured hardware renderer.
#[must_use]
pub fn with_backend(
backend: GraphicsBackend,
width: u32,
height: u32,
config: RenderConfig,
enable_readback: bool,
) -> Self {
Self::with_backend_and_font(
backend,
width,
height,
config,
enable_readback,
NativeSystemFont::deterministic(),
)
}
/// Creates a hardware renderer bound to `backend` with an explicit font provider for readback.
///
/// # Arguments
///
/// - `GraphicsBackend` - Selected GPU backend.
/// - `u32` - Initial physical width.
/// - `u32` - Initial physical height.
/// - `RenderConfig` - Rendering configuration.
/// - `bool` - Whether software readback mirror is enabled.
/// - `NativeSystemFont` - Font provider used by the software readback mirror.
///
/// # Returns
///
/// - `Self` - Configured hardware renderer.
#[must_use]
pub fn with_backend_and_font(
backend: GraphicsBackend,
width: u32,
height: u32,
config: RenderConfig,
enable_readback: bool,
font_provider: NativeSystemFont,
) -> Self {
let driver: NativeGpuDriver = NativeGpuDriver::probe(backend);
let per_glyph_atlas: bool = config.get_direct_gpu_present();
let mut batches: Vec<GpuBatch> = Vec::with_capacity(16);
for _ in 0..8usize {
let mut batch: GpuBatch = GpuBatch::default();
batch.get_mut_primitives().reserve(256);
batches.push(batch);
}
Self {
driver,
batches,
active_batches: 0,
clip_stack: Vec::with_capacity(16),
last_submitted_batches: 0,
last_coalesced_merges: 0,
last_culled_instances: 0,
last_uploaded_instances: 0,
last_uploaded_bytes: 0,
readback: SoftwareRenderer::with_font_provider(width, height, config, font_provider),
enable_readback,
resource_ring: GpuResourceRing::default(),
direct_gpu_frames: 0,
cpu_readback_frames: 0,
last_cpu_rgba_upload_bytes: 0,
has_unsupported_effect: false,
last_fence_id: 0,
blur_passes: Vec::with_capacity(8),
active_scroll_offset: [0.0, 0.0],
active_layer_id: 0,
last_uploaded_primitive_bytes: 0,
gpu_glyph_atlas: IncrementalGpuGlyphAtlas::default(),
gpu_image_atlas: IncrementalGpuImageAtlas::default(),
per_glyph_atlas,
}
}
/// Updates the native system font provider forwarded to the internal glyph atlas and CPU readback backend.
///
/// # Arguments
///
/// - `&Self` - Mutable hardware renderer.
/// - `NativeSystemFont` - Host font rasterizer provider.
///
/// # Returns
///
/// - `&mut Self` - Mutable hardware renderer for chaining.
pub fn set_font_provider(&mut self, font_provider: NativeSystemFont) -> &mut Self {
let _: &mut SoftwareRenderer = self.get_mut_readback().set_font_provider(font_provider);
self
}
/// Captures an on-demand CPU reference framebuffer readback without enabling steady-state CPU mirroring.
///
/// # Arguments
///
/// - `&Self` - Mutable hardware renderer.
/// - `&DisplayList` - Display list to rasterize through the CPU reference backend.
/// - `DamageRegion` - Damage region to rasterize.
///
/// # Returns
///
/// - `&Framebuffer` - Rendered reference RGBA8 framebuffer.
pub fn capture_reference_readback(
&mut self,
display_list: &DisplayList,
damage: DamageRegion,
) -> &Framebuffer {
let (_, _): (usize, usize) = self.get_mut_readback().render(display_list, damage);
self.get_readback().get_framebuffer()
}
/// Signals completion of GPU submission `fence_id` to release staging ring slots and reclaim deferred resources.
///
/// # Arguments
///
/// - `&Self` - Mutable hardware renderer.
/// - `u64` - Completed monotonic GPU fence identifier.
///
/// # Returns
///
/// - `usize` - Number of deferred GPU resources reclaimed.
pub fn complete_gpu_fence(&mut self, fence_id: u64) -> usize {
self.get_mut_resource_ring().complete_fence(fence_id)
}
/// Trims invisible persistent GPU scroll tile caches under memory pressure according to `retain_ratio`.
///
/// # Arguments
///
/// - `&Self` - Mutable hardware renderer.
/// - `f32` - Retained budget fraction in `(0.0..=1.0]`.
///
/// # Returns
///
/// - `usize` - Number of cold scroll tiles evicted to fence-deferred reclamation.
pub fn trim_gpu_caches(&mut self, retain_ratio: f32) -> usize {
self.get_mut_resource_ring()
.apply_retention_ratio(retain_ratio)
}
/// Returns latest-frame GPU batching and upload telemetry `(batches, coalesced_merges, culled_instances, uploaded_instances, uploaded_bytes)`.
///
/// # Arguments
///
/// - `&Self` - Hardware renderer reference.
///
/// # Returns
///
/// - `(usize, usize, usize, usize, usize)` - Latest frame batching and upload telemetry tuple.
#[must_use]
pub fn last_frame_telemetry(&self) -> (usize, usize, usize, usize, usize) {
(
self.get_last_submitted_batches(),
self.get_last_coalesced_merges(),
self.get_last_culled_instances(),
self.get_last_uploaded_instances(),
self.get_last_uploaded_bytes(),
)
}
/// Returns the slice of active `GpuBatch` submissions populated for the latest rendered frame.
///
/// # Arguments
///
/// - `&Self` - Hardware renderer reference.
///
/// # Returns
///
/// - `&[GpuBatch]` - Active order-preserving GPU draw batches.
#[must_use]
pub fn active_batches_slice(&self) -> &[GpuBatch] {
let active: usize = self.get_active_batches().min(self.get_batches().len());
&self.get_batches()[..active]
}
/// Computes a deterministic 64-bit FNV-1a hash over all compiled GPU batch instances.
///
/// # Arguments
///
/// - `&Self` - Hardware renderer reference.
///
/// # Returns
///
/// - `u64` - Deterministic batch geometry hash.
#[must_use]
pub fn batch_hash(&self) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
let active: usize = self.get_active_batches().min(self.get_batches().len());
for batch in self.get_batches()[..active].iter() {
if !batch.get_primitives().is_empty() {
for prim in batch.get_primitives().iter() {
for item_val in prim.get_rect().iter().chain(prim.get_clip_rect().iter()) {
hash ^= item_val.to_bits() as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
for word in [
prim.get_color_rgba(),
prim.get_aux_color_rgba(),
prim.get_kind_flags(),
prim.get_extra_param(),
] {
hash ^= word as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
for lane in prim
.get_uv_rect()
.iter()
.chain(prim.get_radii_border().iter())
{
hash ^= *lane as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
}
} else {
for inst in batch.get_instances().iter() {
for item_val in inst
.get_rect()
.iter()
.chain(inst.get_color().iter())
.chain(inst.get_radii().iter())
{
hash ^= item_val.to_bits() as u64;
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
}
}
}
hash
}
/// Returns `true` when physical quad `quad = [x, y, w, h]` lies completely inside `container`.
///
/// # Arguments
///
/// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
/// - `Rect` - Enclosing physical clip rectangle.
///
/// # Returns
///
/// - `bool` - True when no fragment of `quad` extends outside `container`.
#[inline(always)]
#[must_use]
fn quad_inside_rect(quad: [f32; 4], container: Rect) -> bool {
let qx0: f32 = quad[0];
let qy0: f32 = quad[1];
let qx1: f32 = qx0 + quad[2];
let qy1: f32 = qy0 + quad[3];
let x_in: bool = qx0 >= container.get_x() && qx1 <= container.right();
let y_in: bool = qy0 >= container.get_y() && qy1 <= container.bottom();
container.get_width() > 0.0 && container.get_height() > 0.0 && x_in && y_in
}
/// Returns `true` when `quad` intersects `clip` with strictly positive area.
///
/// # Arguments
///
/// - `[f32; 4]` - Physical quad bounds `[x, y, width, height]`.
/// - `Rect` - Active physical scissor clip.
///
/// # Returns
///
/// - `bool` - True when at least part of `quad` falls inside `clip`.
#[inline(always)]
#[must_use]
fn quad_intersects_clip(quad: [f32; 4], clip: Rect) -> bool {
let qw: f32 = quad[2];
let qh: f32 = quad[3];
let quad_empty: bool = qw <= 0.0 || qh <= 0.0;
let clip_empty: bool = clip.get_width() <= 0.0 || clip.get_height() <= 0.0;
if quad_empty || clip_empty {
return false;
}
let qx0: f32 = quad[0];
let qy0: f32 = quad[1];
let qx1: f32 = qx0 + qw;
let qy1: f32 = qy0 + qh;
let x_hit: bool = qx1 > clip.get_x() && qx0 < clip.right();
let y_hit: bool = qy1 > clip.get_y() && qy0 < clip.bottom();
x_hit && y_hit
}
/// Returns `true` when `inner` lies completely inside `outer`.
///
/// # Arguments
///
/// - `Rect` - Candidate inner rectangle.
/// - `Rect` - Candidate outer enclosing rectangle.
///
/// # Returns
///
/// - `bool` - True when `inner` is contained inside `outer`.
#[inline(always)]
#[must_use]
fn rect_inside_rect(inner: Rect, outer: Rect) -> bool {
let x_in: bool = inner.get_x() >= outer.get_x() && inner.right() <= outer.right();
let y_in: bool = inner.get_y() >= outer.get_y() && inner.bottom() <= outer.bottom();
x_in && y_in
}
/// Returns the union bounding box of `existing` and physical quad `quad = [x, y, w, h]`.
///
/// # Arguments
///
/// - `Rect` - Existing bounding box.
/// - `[f32; 4]` - Newly appended quad bounds `[x, y, width, height]`.
///
/// # Returns
///
/// - `Rect` - Enclosing union rectangle.
#[inline(always)]
#[must_use]
fn union_rect_quad(existing: Rect, quad: [f32; 4]) -> Rect {
let x0: f32 = existing.get_x().min(quad[0]);
let y0: f32 = existing.get_y().min(quad[1]);
let x1: f32 = existing.right().max(quad[0] + quad[2]);
let y1: f32 = existing.bottom().max(quad[1] + quad[3]);
Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
}
/// Compiles `display_list` into order-preserving coalesced GPU instanced batches and submits them to the GPU driver.
///
/// # Arguments
///
/// - `&Self` - Mutable hardware renderer.
/// - `&DisplayList` - Backend-agnostic draw command stream.
/// - `DamageRegion` - Active damage region for readback mirroring.
///
/// # Returns
///
/// - `Result<(usize, usize), PlatformError>` - Tuple of `(draw_batches, pixels_shaded)`.
pub fn render(
&mut self,
display_list: &DisplayList,
damage: DamageRegion,
) -> Result<(usize, usize), PlatformError> {
self.render_with_physical_size(display_list, damage, None)
}
/// Compiles `display_list` into 64-byte `GpuPrimitiveInstance` batches using authoritative physical backing dimensions when provided.
///
/// # Arguments
///
/// - `&Self` - Mutable hardware renderer.
/// - `&DisplayList` - Backend-agnostic draw command stream.
/// - `DamageRegion` - Active damage region for readback mirroring.
/// - `Option<(u32, u32)>` - Authoritative `(physical_width, physical_height)` preventing `(logical * scale).round()` drift.
///
/// # Returns
///
/// - `Result<(usize, usize), PlatformError>` - Tuple of `(draw_batches, pixels_shaded)`.
pub fn render_with_physical_size(
&mut self,
display_list: &DisplayList,
damage: DamageRegion,
physical_size: Option<(u32, u32)>,
) -> Result<(usize, usize), PlatformError> {
let scale: f32 = display_list.get_scale_factor().clamp(0.25, 16.0);
let (phys_w, phys_h): (u32, u32) = match physical_size {
Some((width_px, height_px)) if width_px > 0 && height_px > 0 => (width_px, height_px),
_ => (
((display_list.get_viewport().get_width() * scale).round() as u32).max(1),
((display_list.get_viewport().get_height() * scale).round() as u32).max(1),
),
};
let max_blur_px: f32 = (64.0 * scale).clamp(64.0, 512.0);
let full_clip: Rect = Rect::new(0.0, 0.0, phys_w as f32, phys_h as f32);
let full_entry: GpuClipEntry = GpuClipEntry {
scissor: full_clip,
safe_inner: full_clip,
rounded_clip_bits: 0,
};
let Self {
driver,
batches,
active_batches,
clip_stack,
last_submitted_batches,
last_coalesced_merges,
last_culled_instances,
last_uploaded_instances,
last_uploaded_bytes,
readback,
enable_readback,
resource_ring,
direct_gpu_frames,
cpu_readback_frames,
last_cpu_rgba_upload_bytes,
has_unsupported_effect,
last_fence_id,
blur_passes,
active_scroll_offset,
active_layer_id,
last_uploaded_primitive_bytes,
gpu_glyph_atlas,
gpu_image_atlas,
per_glyph_atlas,
} = self;
gpu_image_atlas.begin_frame();
let glyph_h_before: u32 = gpu_glyph_atlas.get_height();
let img_w_before: u32 = gpu_image_atlas.get_width();
let img_h_before: u32 = gpu_image_atlas.get_height();
clip_stack.clear();
clip_stack.push(full_entry);
blur_passes.clear();
*active_batches = 0;
*has_unsupported_effect = false;
let layer_scroll: [f32; 2] = *active_scroll_offset;
let layer_id: u8 = *active_layer_id;
let gpu_supports_blur: bool = driver.supports_backdrop_blur_pass()
|| matches!(
driver.backend(),
GraphicsBackend::Metal
| GraphicsBackend::WebGl2
| GraphicsBackend::OpenGlEs
| GraphicsBackend::WebGpu
| GraphicsBackend::Vulkan
| GraphicsBackend::Direct3D12
| GraphicsBackend::Direct3D11
);
let mut tail_state: GpuBatchCoalesceState = GpuBatchCoalesceState {
scroll_offset: layer_scroll,
layer_id,
..GpuBatchCoalesceState::default()
};
let mut coalesced_merges: usize = 0;
let mut culled_instances: usize = 0;
let mut uploaded_instances: usize = 0;
let mut clear_color: Color = COLOR_WHITE;
for cmd in display_list.get_commands().iter() {
let clip_entry: GpuClipEntry = clip_stack.last().copied().unwrap_or(full_entry);
let active_clip: Rect = clip_entry.scissor;
match cmd {
DrawCommand::Clear(color_item) => {
clear_color = *color_item;
}
DrawCommand::PushClip(rect) => {
let phys: Rect = snap_physical_rect(*rect, scale);
let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
let next_safe: Rect = clip_entry.safe_inner.intersect(phys).unwrap_or_default();
let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
active_clip,
clip_entry.rounded_clip_bits,
next_scissor,
phys,
None,
);
clip_stack.push(GpuClipEntry {
scissor: next_scissor,
safe_inner: next_safe,
rounded_clip_bits: next_bits,
});
}
DrawCommand::PushRoundedClip { rect, radius } => {
let phys: Rect = snap_physical_rect(*rect, scale);
let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
let phys_radius: CornerRadius = CornerRadius::new(
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
);
let max_r: f32 = phys_radius.max_radius().ceil();
let inset_w: f32 = (phys.get_width() - max_r * 2.0).max(0.0);
let inset_h: f32 = (phys.get_height() - max_r * 2.0).max(0.0);
let rounded_safe: Rect =
Rect::new(phys.get_x() + max_r, phys.get_y() + max_r, inset_w, inset_h);
let next_safe: Rect = clip_entry
.safe_inner
.intersect(rounded_safe)
.unwrap_or_default();
let next_bits: u16 = GpuPrimitiveInstance::encode_rounded_clip_bits(
active_clip,
clip_entry.rounded_clip_bits,
next_scissor,
phys,
Some(phys_radius),
);
clip_stack.push(GpuClipEntry {
scissor: next_scissor,
safe_inner: next_safe,
rounded_clip_bits: next_bits,
});
}
DrawCommand::PopClip => {
if clip_stack.len() > 1 {
let _: Option<GpuClipEntry> = clip_stack.pop();
}
}
DrawCommand::FillRoundedRect {
rect,
color,
radius,
border,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let border_width: f32 = if border.get_width() > 0.0 {
(border.get_width() * scale).max(1.0)
} else {
0.0
};
let inst: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: color.to_f32_array(),
secondary_color: border.get_color().to_f32_array(),
radii: [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
],
stroke_or_blur: border_width,
angle_rad: 0.0,
kind: GpuPrimitiveKind::RoundedRect as u32,
reserved: 0,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
inst,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::LinearGradientRect {
rect,
gradient,
radius,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let inst: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: gradient.get_start_color().to_f32_array(),
secondary_color: gradient.get_end_color().to_f32_array(),
radii: [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
],
stroke_or_blur: 0.0,
angle_rad: gradient.get_angle_deg().to_radians(),
kind: GpuPrimitiveKind::Gradient as u32,
reserved: 0,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
inst,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::BoxShadow {
rect,
radius,
shadow,
} => {
let spread: f32 = shadow.get_spread_radius() * scale;
let blur: f32 = (shadow.get_blur_radius().max(0.5) * scale).min(max_blur_px);
let sigma: f32 = (blur * 0.5).max(0.75);
let pad: f32 = (sigma * 3.0).ceil();
let base_rect: Rect = snap_physical_rect(*rect, scale);
let caster_x: f32 =
base_rect.get_x() + (shadow.get_offset_x() * scale).round() - spread;
let caster_y: f32 =
base_rect.get_y() + (shadow.get_offset_y() * scale).round() - spread;
let caster_w: f32 = (base_rect.get_width() + spread * 2.0).max(1.0);
let caster_h: f32 = (base_rect.get_height() + spread * 2.0).max(1.0);
let quad: [f32; 4] = [
caster_x - pad,
caster_y - pad,
caster_w + pad * 2.0,
caster_h + pad * 2.0,
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let inst: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: shadow.get_color().to_f32_array(),
secondary_color: [0.0; 4],
radii: [
(radius.get_top_left() * scale + spread).max(0.0),
(radius.get_top_right() * scale + spread).max(0.0),
(radius.get_bottom_right() * scale + spread).max(0.0),
(radius.get_bottom_left() * scale + spread).max(0.0),
],
stroke_or_blur: sigma,
angle_rad: pad,
kind: GpuPrimitiveKind::Shadow as u32,
reserved: 0,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
inst,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::BackdropBlur {
rect,
radius,
blur_radius,
} => {
if !gpu_supports_blur {
*has_unsupported_effect = true;
}
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let phys_blur: f32 = (*blur_radius * scale).clamp(0.5, max_blur_px);
let radii_px: [f32; 4] = [
radius.get_top_left() * scale,
radius.get_top_right() * scale,
radius.get_bottom_right() * scale,
radius.get_bottom_left() * scale,
];
let halo: Rect = Rect::new(
(snapped.get_x() - phys_blur).max(0.0),
(snapped.get_y() - phys_blur).max(0.0),
(snapped.get_width() + phys_blur * 2.0).min(phys_w as f32),
(snapped.get_height() + phys_blur * 2.0).min(phys_h as f32),
);
blur_passes.push(GpuBackdropBlurPass {
bounds: snapped,
input_bounds: halo,
clip_rect: active_clip,
radii: radii_px,
blur_radius: phys_blur,
layer_id,
});
let inv_vp_w: f32 = 1.0 / (phys_w.max(1) as f32);
let inv_vp_h: f32 = 1.0 / (phys_h.max(1) as f32);
let blur_uv: [u16; 4] = [
(snapped.get_x() * inv_vp_w * 65535.0)
.round()
.clamp(0.0, 65535.0) as u16,
(snapped.get_y() * inv_vp_h * 65535.0)
.round()
.clamp(0.0, 65535.0) as u16,
(snapped.right() * inv_vp_w * 65535.0)
.round()
.clamp(0.0, 65535.0) as u16,
(snapped.bottom() * inv_vp_h * 65535.0)
.round()
.clamp(0.0, 65535.0) as u16,
];
let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
let blur_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
rect: quad,
clip_rect: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
aux_color_rgba: 0,
uv_rect: blur_uv,
radii_border: [
GpuPrimitiveInstance::pack_u16_q4(radii_px[0].min(radius_cap)),
GpuPrimitiveInstance::pack_u16_q4(radii_px[1].min(radius_cap)),
GpuPrimitiveInstance::pack_u16_q4(radii_px[2].min(radius_cap)),
GpuPrimitiveInstance::pack_u16_q4(radii_px[3].min(radius_cap)),
],
kind_flags: GpuPrimitiveInstance::pack_kind_flags(
PrimKind::BackdropBlur,
0,
0,
tail_state.layer_id,
),
extra_param: GpuPrimitiveInstance::pack_f16x2(phys_blur, 0.0),
};
Self::push_primitive_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
blur_prim,
true,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::TextRun { rect, text, style } => {
let run_quad: [f32; 4] = [
rect.get_x() * scale,
rect.get_y() * scale,
rect.get_width() * scale,
rect.get_height() * scale,
];
if !Self::quad_intersects_clip(run_quad, active_clip) {
culled_instances += 1;
continue;
}
if *per_glyph_atlas {
let wrap_w: Option<f32> = if style.get_overflow() == TextOverflow::Wrap {
Some(rect.get_width().max(1.0))
} else {
None
};
let layout_res: TextLayoutResult =
DeterministicTextMeasurer.measure(text, *style, wrap_w);
let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
let letter_sp: f32 = style.get_letter_spacing() * scale;
let line_h_phys: f32 = layout_res.get_line_height_px() * scale;
let font_provider: NativeSystemFont = readback.get_font_provider().clone();
let cpu_atlas: &mut GlyphAtlas = readback.get_mut_glyph_atlas();
let text_color_u32: u32 =
GpuPrimitiveInstance::pack_color_rgba8(style.get_color());
let clip_arr: [f32; 4] = [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
];
let box_w_phys: f32 = rect.get_width() * scale;
let base_x_phys: f32 = (rect.get_x() * scale).round();
let mut line_glyphs: Vec<(Option<GpuGlyphPlacement>, f32)> =
Vec::with_capacity(32);
for (line_idx, line) in layout_res.get_lines().iter().enumerate() {
let line_y: f32 =
(rect.get_y() * scale + (line_idx as f32) * line_h_phys).round();
line_glyphs.clear();
let mut actual_line_w: f32 = 0.0;
for ch in line.get_text().chars() {
if ch == ' ' || ch == '\t' {
let space_adv: f32 =
measure_char_advance(ch, *style) * scale + letter_sp;
actual_line_w += space_adv;
line_glyphs.push((None, space_adv));
} else {
let key: GlyphKey =
GlyphKey::from_text_style(ch, phys_font_px, *style);
let raster: &RasterizedGlyph =
cpu_atlas.get_or_rasterize_with(key, &font_provider);
let adv_phys: f32 =
(raster.get_advance() as f32).max(1.0) + letter_sp;
let placement: GpuGlyphPlacement =
gpu_glyph_atlas.insert_or_get(key, raster);
actual_line_w += adv_phys;
line_glyphs.push((Some(placement), adv_phys));
}
}
let fit_scale: f32 =
if box_w_phys > 1.0 && actual_line_w > box_w_phys + 1.0 {
(box_w_phys / actual_line_w).clamp(0.72, 1.0)
} else {
1.0
};
let fitted_w: f32 = actual_line_w * fit_scale;
let align_x: f32 = match style.get_align() {
TextAlign::Left => 0.0,
TextAlign::Center => ((box_w_phys - fitted_w) * 0.5).max(0.0),
TextAlign::Right => (box_w_phys - fitted_w).max(0.0),
};
let mut pen_x: f32 = base_x_phys + align_x.round();
for &(placement_opt, adv_phys) in line_glyphs.iter() {
if let Some(placement) = placement_opt
&& placement.get_width() > 0
&& placement.get_height() > 0
{
let gw: f32 = placement.get_width() as f32;
let gh: f32 = placement.get_height() as f32;
let glyph_y: f32 = line_y + ((line_h_phys - gh) * 0.5).round();
let glyph_quad: [f32; 4] = [pen_x.round(), glyph_y, gw, gh];
if Self::quad_intersects_clip(glyph_quad, active_clip) {
let kind_flags: u32 = GpuPrimitiveInstance::pack_kind_flags(
PrimKind::GlyphAlpha8,
0,
0,
tail_state.layer_id,
);
let glyph_prim: GpuPrimitiveInstance =
GpuPrimitiveInstance {
rect: glyph_quad,
clip_rect: clip_arr,
color_rgba: text_color_u32,
aux_color_rgba: 0,
uv_rect: placement.get_uv_rect(),
radii_border: [0; 4],
kind_flags,
extra_param: 0,
};
Self::push_primitive_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
glyph_prim,
false,
&mut coalesced_merges,
);
uploaded_instances += 1;
} else {
culled_instances += 1;
}
}
pen_x += adv_phys * fit_scale;
}
}
} else {
let glyph_count: usize = if text.is_ascii() {
text.as_bytes()
.iter()
.filter(|byte_item: &&u8| **byte_item != b' ')
.count()
.max(1)
} else {
text.chars()
.filter(|char_item: &char| *char_item != ' ')
.count()
.max(1)
};
let text_instance: GpuQuadInstance = GpuQuadInstance {
rect: run_quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: style.get_color().to_f32_array(),
secondary_color: [0.0; 4],
radii: [0.0; 4],
stroke_or_blur: style.get_font_size() * scale,
angle_rad: 0.0,
kind: GpuPrimitiveKind::Glyph as u32,
reserved: glyph_count as u32,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
text_instance,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
}
DrawCommand::TextCaret {
text_rect,
content_rect,
text,
style,
caret_height,
color,
multiline,
} => {
if active_clip.get_width() <= 0.0 || active_clip.get_height() <= 0.0 {
culled_instances += 1;
continue;
}
let meas: TextLayoutResult = DeterministicTextMeasurer.measure(
text,
*style,
if *multiline {
Some(content_rect.get_width().max(1.0))
} else {
None
},
);
let phys_font_px: f32 = (style.get_font_size() * scale).max(6.0);
let letter_sp: f32 = style.get_letter_spacing() * scale;
let last_w_phys: f32 = if let Some(line) = meas.get_lines().last() {
let font_provider: NativeSystemFont = readback.get_font_provider().clone();
let atlas: &mut GlyphAtlas = readback.get_mut_glyph_atlas();
let mut acc: f32 = 0.0;
for ch in line.get_text().chars() {
if ch == ' ' || ch == '\t' {
acc += measure_char_advance(ch, *style) * scale + letter_sp;
} else {
let key: GlyphKey =
GlyphKey::from_text_style(ch, phys_font_px, *style);
let green_val: &RasterizedGlyph =
atlas.get_or_rasterize_with(key, &font_provider);
acc += (green_val.get_advance() as f32).max(1.0) + letter_sp;
}
}
acc
} else {
0.0
};
let line_idx: usize = meas.get_lines().len().saturating_sub(1);
let trailing_gap_phys: f32 = if last_w_phys > 0.0 { 1.0 * scale } else { 0.0 };
let min_x_phys: f32 = content_rect.get_x() * scale;
let max_x_phys: f32 = ((content_rect.right() - 2.0) * scale).max(min_x_phys);
let caret_x_phys: f32 =
(text_rect.get_x() * scale + last_w_phys + trailing_gap_phys)
.min(max_x_phys)
.max(min_x_phys);
let caret_y: f32 = if *multiline {
(content_rect.get_y()
+ (line_idx as f32) * meas.get_line_height_px()
+ ((meas.get_line_height_px() - caret_height) * 0.5).max(0.0))
.min(content_rect.bottom() - caret_height)
.max(content_rect.get_y())
} else {
content_rect.get_y()
+ ((content_rect.get_height() - caret_height) * 0.5).max(0.0)
};
let quad: [f32; 4] = [
caret_x_phys.round(),
(caret_y * scale).round(),
(1.5 * scale).max(1.0),
(caret_height * scale).max(2.0),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let inst: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: color.to_f32_array(),
secondary_color: [0.0; 4],
radii: [0.5 * scale; 4],
stroke_or_blur: 0.0,
angle_rad: 0.0,
kind: GpuPrimitiveKind::RoundedRect as u32,
reserved: 0,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
inst,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::Image {
rect,
buffer,
radius,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let uv_rect: [u16; 4] = gpu_image_atlas
.insert_or_get(
buffer.get_width(),
buffer.get_height(),
buffer.get_pixels().as_ref(),
)
.map_or([0, 0, u16::MAX, u16::MAX], |slot: GpuImagePlacement| {
slot.get_uv_rect()
});
let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
let img_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
rect: quad,
clip_rect: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
aux_color_rgba: 0,
uv_rect,
radii_border: [
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_top_left() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_top_right() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_bottom_right() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_bottom_left() * scale).min(radius_cap),
),
],
kind_flags: GpuPrimitiveInstance::pack_kind_flags(
PrimKind::ImageTexture,
0,
0,
tail_state.layer_id,
),
extra_param: 0,
};
Self::push_primitive_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
img_prim,
false,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::SharedImage {
rect,
width,
height,
pixels,
radius,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let uv_rect: [u16; 4] = gpu_image_atlas
.insert_or_get(*width, *height, pixels.as_slice())
.map_or([0, 0, u16::MAX, u16::MAX], |slot: GpuImagePlacement| {
slot.get_uv_rect()
});
let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
let img_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
rect: quad,
clip_rect: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
aux_color_rgba: 0,
uv_rect,
radii_border: [
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_top_left() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_top_right() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_bottom_right() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_bottom_left() * scale).min(radius_cap),
),
],
kind_flags: GpuPrimitiveInstance::pack_kind_flags(
PrimKind::ImageTexture,
0,
0,
tail_state.layer_id,
),
extra_param: 0,
};
Self::push_primitive_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
img_prim,
false,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::Circle {
center,
radius,
color,
} => {
let red_val: f32 = radius * scale;
let pad: f32 = 1.5;
let extent: f32 = red_val + pad;
let quad: [f32; 4] = [
center.get_x() * scale - extent,
center.get_y() * scale - extent,
extent * 2.0,
extent * 2.0,
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let inst: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: color.to_f32_array(),
secondary_color: [0.0; 4],
radii: [red_val; 4],
stroke_or_blur: red_val,
angle_rad: 0.0,
kind: GpuPrimitiveKind::Circle as u32,
reserved: 0,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
inst,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::Line {
from,
to,
color,
width,
} => {
let fx0: f32 = from.get_x() * scale;
let fy0: f32 = from.get_y() * scale;
let fx1: f32 = to.get_x() * scale;
let fy1: f32 = to.get_y() * scale;
let dx: f32 = fx1 - fx0;
let dy: f32 = fy1 - fy0;
let stroke_px: f32 = (width * scale).max(1.0);
let pad: f32 = stroke_px * 0.5 + 1.5;
let min_x: f32 = fx0.min(fx1) - pad;
let min_y: f32 = fy0.min(fy1) - pad;
let max_x: f32 = fx0.max(fx1) + pad;
let max_y: f32 = fy0.max(fy1) + pad;
let quad: [f32; 4] = [
min_x,
min_y,
(max_x - min_x).max(2.0),
(max_y - min_y).max(2.0),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let inst: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: color.to_f32_array(),
secondary_color: [0.0; 4],
radii: [fx0, fy0, fx1, fy1],
stroke_or_blur: stroke_px,
angle_rad: dy.atan2(dx),
kind: GpuPrimitiveKind::Line as u32,
reserved: 0,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
inst,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::Triangle { p0, p1, p2, color } => {
let min_x: f32 = p0.get_x().min(p1.get_x()).min(p2.get_x()) * scale - 1.5;
let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale - 1.5;
let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale + 1.5;
let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale + 1.5;
let quad: [f32; 4] = [
min_x,
min_y,
(max_x - min_x).max(2.0),
(max_y - min_y).max(2.0),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let inst: GpuQuadInstance = GpuQuadInstance {
rect: quad,
clip: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color: color.to_f32_array(),
secondary_color: [p0.get_x() * scale, p0.get_y() * scale, 0.0, 0.0],
radii: [
p1.get_x() * scale,
p1.get_y() * scale,
p2.get_x() * scale,
p2.get_y() * scale,
],
stroke_or_blur: 0.0,
angle_rad: 0.0,
kind: GpuPrimitiveKind::Triangle as u32,
reserved: 3,
};
Self::push_instance_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
inst,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::SpriteRegion {
rect,
buffer,
src_rect,
tint,
} => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let uv_rect: [u16; 4] = gpu_image_atlas
.insert_or_get(
buffer.get_width(),
buffer.get_height(),
buffer.get_pixels().as_ref(),
)
.map_or([0, 0, u16::MAX, u16::MAX], |slot: GpuImagePlacement| {
gpu_image_atlas.sub_uv_rect(
slot,
buffer.get_width(),
buffer.get_height(),
*src_rect,
)
});
let sprite_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
rect: quad,
clip_rect: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color_rgba: GpuPrimitiveInstance::pack_color_rgba8(*tint),
aux_color_rgba: 0,
uv_rect,
radii_border: [0; 4],
kind_flags: GpuPrimitiveInstance::pack_kind_flags(
PrimKind::ImageTexture,
0,
0,
tail_state.layer_id,
),
extra_param: 0,
};
Self::push_primitive_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
sprite_prim,
false,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
DrawCommand::ExternalSurface { rect, radius } => {
let snapped: Rect = snap_physical_rect(*rect, scale);
let quad: [f32; 4] = [
snapped.get_x(),
snapped.get_y(),
snapped.get_width(),
snapped.get_height(),
];
if !Self::quad_intersects_clip(quad, active_clip) {
culled_instances += 1;
continue;
}
let radius_cap: f32 = GpuPrimitiveInstance::corner_radius_cap(quad, 0, 0.0);
let ext_prim: GpuPrimitiveInstance = GpuPrimitiveInstance {
rect: quad,
clip_rect: [
active_clip.get_x(),
active_clip.get_y(),
active_clip.right(),
active_clip.bottom(),
],
color_rgba: GpuPrimitiveInstance::pack_color_rgba8(COLOR_WHITE),
aux_color_rgba: 0,
uv_rect: [0, 0, u16::MAX, u16::MAX],
radii_border: [
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_top_left() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_top_right() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_bottom_right() * scale).min(radius_cap),
),
GpuPrimitiveInstance::pack_u16_q4(
(radius.get_bottom_left() * scale).min(radius_cap),
),
],
kind_flags: GpuPrimitiveInstance::pack_kind_flags(
PrimKind::ExternalGpuSurface,
0,
0,
tail_state.layer_id,
),
extra_param: 0,
};
Self::push_primitive_coalesced(
batches,
active_batches,
&mut tail_state,
clip_entry,
ext_prim,
false,
&mut coalesced_merges,
);
uploaded_instances += 1;
}
}
}
let glyph_h_after: u32 = gpu_glyph_atlas.get_height();
let img_w_after: u32 = gpu_image_atlas.get_width();
let img_h_after: u32 = gpu_image_atlas.get_height();
if glyph_h_after != glyph_h_before && glyph_h_after > 0 {
let v_scale: f32 = (glyph_h_before as f32) / (glyph_h_after as f32);
for batch in batches.iter_mut().take(*active_batches) {
for prim in batch.get_mut_primitives().iter_mut() {
if prim.prim_kind() == PrimKind::GlyphAlpha8 {
let mut uv: [u16; 4] = prim.get_uv_rect();
uv[1] = ((f32::from(uv[1]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
uv[3] = ((f32::from(uv[3]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
prim.set_uv_rect(uv);
}
}
}
}
if (img_w_after != img_w_before || img_h_after != img_h_before)
&& img_w_after > 0
&& img_h_after > 0
{
let u_scale: f32 = (img_w_before as f32) / (img_w_after as f32);
let v_scale: f32 = (img_h_before as f32) / (img_h_after as f32);
for batch in batches.iter_mut().take(*active_batches) {
for prim in batch.get_mut_primitives().iter_mut() {
if prim.prim_kind() == PrimKind::ImageTexture {
let mut uv: [u16; 4] = prim.get_uv_rect();
uv[0] = ((f32::from(uv[0]) * u_scale).round().clamp(0.0, 65535.0)) as u16;
uv[1] = ((f32::from(uv[1]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
uv[2] = ((f32::from(uv[2]) * u_scale).round().clamp(0.0, 65535.0)) as u16;
uv[3] = ((f32::from(uv[3]) * v_scale).round().clamp(0.0, 65535.0)) as u16;
prim.set_uv_rect(uv);
}
}
}
}
let prim_upload_bytes: usize =
uploaded_instances.saturating_mul(GPU_PRIMITIVE_INSTANCE_BYTES);
let upload_bytes: usize = prim_upload_bytes;
let acquired_fence: u64 = match resource_ring
.acquire_staging(prim_upload_bytes, GpuUploadPriority::RequiredFrame)
{
GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
GpuRingAcquireResult::DeferredFrameRingFull
| GpuRingAcquireResult::DroppedPrefetchRingFull => {
let prev: u64 =
GpuResourceRing::next_monotonic_fence(resource_ring.get_completed_fence_id());
let _: usize = resource_ring.complete_fence(prev);
match resource_ring
.acquire_staging(prim_upload_bytes, GpuUploadPriority::RequiredFrame)
{
GpuRingAcquireResult::Acquired { fence_id, .. } => fence_id,
GpuRingAcquireResult::DeferredFrameRingFull
| GpuRingAcquireResult::DroppedPrefetchRingFull => {
resource_ring.get_next_fence_id()
}
}
}
};
let _: usize = gpu_glyph_atlas.flush_to_driver(driver);
if !blur_passes.is_empty() && driver.supports_backdrop_blur_pass() {
let _: usize = driver.execute_dual_kawase_blur_passes(phys_w, phys_h, blur_passes);
}
let active_slice: &[GpuBatch] = &batches[..(*active_batches).min(batches.len())];
let submitted: usize = driver.submit_batches(phys_w, phys_h, clear_color, active_slice)?;
*last_fence_id = acquired_fence;
let hw_done: u64 = completed_gpu_fence();
if driver.get_device_handle() != 0 && hw_done > 0 {
let _: usize = resource_ring.complete_fence(hw_done.min(acquired_fence));
} else {
let retire_window: u64 = acquired_fence.saturating_sub(2);
if retire_window > 0 {
let _: usize = resource_ring.complete_fence(retire_window);
}
}
*last_submitted_batches = submitted;
*last_coalesced_merges = coalesced_merges;
*last_culled_instances = culled_instances;
*last_uploaded_instances = uploaded_instances;
*last_uploaded_bytes = upload_bytes;
*last_uploaded_primitive_bytes = prim_upload_bytes;
let pixels: usize = if *enable_readback {
let (_, px): (usize, usize) = readback.render(display_list, damage);
*cpu_readback_frames = cpu_readback_frames.saturating_add(1);
*last_cpu_rgba_upload_bytes = (phys_w as usize)
.saturating_mul(phys_h as usize)
.saturating_mul(4);
px
} else {
*direct_gpu_frames = direct_gpu_frames.saturating_add(1);
*last_cpu_rgba_upload_bytes = 0;
(phys_w as usize).saturating_mul(phys_h as usize)
};
Ok((submitted, pixels))
}
/// Converts `instance` into a 64-byte `GpuPrimitiveInstance` and appends it without allocating legacy 96-byte quad storage.
///
/// # Arguments
///
/// - `&mut Vec<GpuBatch>` - Persistent batch pool vector.
/// - `&mut usize` - Active batch watermark for the current frame.
/// - `&mut GpuBatchCoalesceState` - Unclipped containment and layer metadata for the active tail batch.
/// - `GpuClipEntry` - Active physical scissor and corner-free interior safe clip rectangle.
/// - `GpuQuadInstance` - Instance data compiled into 64-byte `GpuPrimitiveInstance`.
/// - `&mut usize` - Running counter of cross-clip batch splits avoided by coalescing.
fn push_instance_coalesced(
batches: &mut Vec<GpuBatch>,
active_batches: &mut usize,
tail_state: &mut GpuBatchCoalesceState,
clip_entry: GpuClipEntry,
instance: GpuQuadInstance,
coalesced_merges: &mut usize,
) {
let is_blur: bool = instance.kind == GpuPrimitiveKind::BackdropBlur as u32;
let base_prim: GpuPrimitiveInstance =
GpuPrimitiveInstance::from_quad_instance(&instance, 0, tail_state.layer_id);
Self::push_primitive_coalesced(
batches,
active_batches,
tail_state,
clip_entry,
base_prim,
is_blur,
coalesced_merges,
);
}
/// Appends a 64-byte `GpuPrimitiveInstance` directly into the tail `GpuBatch` with zero legacy 96-byte `instances` duplication.
///
/// # Arguments
///
/// - `&mut Vec<GpuBatch>` - Persistent batch pool vector.
/// - `&mut usize` - Active batch watermark for the current frame.
/// - `&mut GpuBatchCoalesceState` - Unclipped containment and layer metadata for the active tail batch.
/// - `GpuClipEntry` - Active physical scissor and corner-free interior safe clip rectangle.
/// - `GpuPrimitiveInstance` - Tightly packed 64-byte GPU primitive record.
/// - `bool` - True when the primitive is a backdrop blur boundary.
/// - `&mut usize` - Running counter of cross-clip batch splits avoided by coalescing.
fn push_primitive_coalesced(
batches: &mut Vec<GpuBatch>,
active_batches: &mut usize,
tail_state: &mut GpuBatchCoalesceState,
clip_entry: GpuClipEntry,
base_prim: GpuPrimitiveInstance,
is_blur: bool,
coalesced_merges: &mut usize,
) {
let scissor: Rect = clip_entry.scissor;
let quad_rect: [f32; 4] = base_prim.get_rect();
let inst_unclipped: bool =
!is_blur && Self::quad_inside_rect(quad_rect, clip_entry.safe_inner);
let prim: GpuPrimitiveInstance = if inst_unclipped {
base_prim
} else {
base_prim.with_rounded_clip_bits(clip_entry.rounded_clip_bits)
};
let count: usize = *active_batches;
if count > 0 {
let last: &mut GpuBatch = &mut batches[count - 1];
if last.get_primitives().len() < MAX_QUADS_PER_BATCH
&& last.get_layer_id() == tail_state.layer_id
&& last.get_scroll_offset() == tail_state.scroll_offset
{
let last_scissor: Rect = last.get_scissor();
let blur_boundary: bool = tail_state.has_backdrop_blur || is_blur;
if last_scissor == scissor && !blur_boundary {
last.get_mut_primitives().push(prim);
tail_state.all_unclipped = tail_state.all_unclipped && inst_unclipped;
tail_state.bounds = Self::union_rect_quad(tail_state.bounds, quad_rect);
return;
}
if !blur_boundary
&& inst_unclipped
&& Self::quad_inside_rect(quad_rect, last_scissor)
{
last.get_mut_primitives().push(prim);
tail_state.bounds = Self::union_rect_quad(tail_state.bounds, quad_rect);
*coalesced_merges += 1;
return;
}
if !blur_boundary
&& tail_state.all_unclipped
&& Self::rect_inside_rect(tail_state.bounds, scissor)
{
last.set_scissor(scissor);
last.get_mut_primitives().push(prim);
tail_state.all_unclipped = inst_unclipped;
tail_state.bounds = Self::union_rect_quad(tail_state.bounds, quad_rect);
*coalesced_merges += 1;
return;
}
}
}
if count < batches.len() {
let slot: &mut GpuBatch = &mut batches[count];
slot.set_scissor(scissor);
slot.set_scroll_offset(tail_state.scroll_offset);
slot.set_layer_id(tail_state.layer_id);
slot.get_mut_instances().clear();
slot.get_mut_primitives().clear();
slot.get_mut_primitives().push(prim);
} else {
let mut batch: GpuBatch = GpuBatch::default();
batch.set_scissor(scissor);
batch.set_scroll_offset(tail_state.scroll_offset);
batch.set_layer_id(tail_state.layer_id);
batch.get_mut_primitives().reserve(512);
batch.get_mut_primitives().push(prim);
batches.push(batch);
}
*active_batches = count + 1;
tail_state.all_unclipped = inst_unclipped;
tail_state.has_backdrop_blur = is_blur;
tail_state.bounds = Rect::new(quad_rect[0], quad_rect[1], quad_rect[2], quad_rect[3]);
}
}