euv-core 0.47.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
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 r: u32 = (rgba[0].clamp(0.0, 1.0) * 255.0).round() as u32;
        let g: u32 = (rgba[1].clamp(0.0, 1.0) * 255.0).round() as u32;
        let b: u32 = (rgba[2].clamp(0.0, 1.0) * 255.0).round() as u32;
        let a: u32 = (rgba[3].clamp(0.0, 1.0) * 255.0).round() as u32;
        r | (g << 8) | (b << 16) | (a << 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_r() as u32)
            | ((color.get_g() as u32) << 8)
            | ((color.get_b() as u32) << 16)
            | ((color.get_a() 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,
            _ => 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
    }

    /// 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 r: [f32; 4] = quad.get_radii();
                uv_rect = [
                    (((r[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
                    (((r[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
                    (((r[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
                    (((r[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 r: [f32; 4] = quad.get_radii();
                aux_color_rgba = Self::pack_rgba8_f32([
                    ((p0[0] - rect[0]) * inv_w).clamp(0.0, 1.0),
                    ((p0[1] - rect[1]) * inv_h).clamp(0.0, 1.0),
                    0.0,
                    1.0,
                ]);
                uv_rect = [
                    (((r[0] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
                    (((r[1] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
                    (((r[2] - rect[0]) * inv_w).clamp(0.0, 1.0) * 65535.0).round() as u16,
                    (((r[3] - rect[1]) * inv_h).clamp(0.0, 1.0) * 65535.0).round() as u16,
                ];
                radii_border = [0; 4];
                (PrimKind::VectorShape, VectorSubKind::Triangle as u16)
            }
            8 => (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, b: &GpuBatch| {
            acc + b.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 mut batches: Vec<GpuBatch> = Vec::with_capacity(16);
        for _ in 0..8usize {
            let mut batch: GpuBatch = GpuBatch::default();
            batch.get_mut_instances().reserve(256);
            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,
        }
    }

    /// 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() {
            for inst in batch.get_instances().iter() {
                for v in inst
                    .get_rect()
                    .iter()
                    .chain(inst.get_color().iter())
                    .chain(inst.get_radii().iter())
                {
                    hash ^= v.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> {
        let scale: f32 = display_list.get_scale_factor().max(0.5);
        let phys_w: u32 = ((display_list.get_viewport().get_width() * scale).round() as u32).max(1);
        let phys_h: u32 =
            ((display_list.get_viewport().get_height() * scale).round() as u32).max(1);
        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,
        };
        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,
        } = self;
        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();
        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(c) => {
                    clear_color = *c;
                }
                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();
                    clip_stack.push(GpuClipEntry {
                        scissor: next_scissor,
                        safe_inner: next_safe,
                    });
                }
                DrawCommand::PushRoundedClip { rect, radius } => {
                    let phys: Rect = snap_physical_rect(*rect, scale);
                    let next_scissor: Rect = active_clip.intersect(phys).unwrap_or_default();
                    let max_r: f32 = (radius.max_radius() * scale).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();
                    clip_stack.push(GpuClipEntry {
                        scissor: next_scissor,
                        safe_inner: next_safe,
                    });
                }
                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 bw: 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: bw,
                        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(96.0);
                    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, 96.0);
                    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 inst: GpuQuadInstance = GpuQuadInstance {
                        rect: quad,
                        clip: [
                            active_clip.get_x(),
                            active_clip.get_y(),
                            active_clip.right(),
                            active_clip.bottom(),
                        ],
                        color: [1.0, 1.0, 1.0, 1.0],
                        secondary_color: [0.0; 4],
                        radii: radii_px,
                        stroke_or_blur: phys_blur,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::BackdropBlur as u32,
                        reserved: 0,
                    };
                    Self::push_instance_coalesced(
                        batches,
                        active_batches,
                        &mut tail_state,
                        clip_entry,
                        inst,
                        &mut coalesced_merges,
                    );
                    uploaded_instances += 1;
                }
                DrawCommand::TextRun { rect, text, style } => {
                    let quad: [f32; 4] = [
                        rect.get_x() * scale,
                        rect.get_y() * scale,
                        rect.get_width() * scale,
                        rect.get_height() * scale,
                    ];
                    if !Self::quad_intersects_clip(quad, active_clip) {
                        culled_instances += 1;
                        continue;
                    }
                    let glyph_count: usize = if text.is_ascii() {
                        text.as_bytes()
                            .iter()
                            .filter(|b: &&u8| **b != b' ')
                            .count()
                            .max(1)
                    } else {
                        text.chars().filter(|c: &char| *c != ' ').count().max(1)
                    };
                    let inst: GpuQuadInstance = GpuQuadInstance {
                        rect: 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,
                        inst,
                        &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 last_w: f32 = meas
                        .get_lines()
                        .last()
                        .map(TextLine::get_width)
                        .unwrap_or(0.0);
                    let line_idx: usize = meas.get_lines().len().saturating_sub(1);
                    let trailing_gap: f32 = if last_w > 0.0 { 1.5 } else { 0.0 };
                    let min_x: f32 = content_rect.get_x();
                    let max_x: f32 = (content_rect.right() - 2.0).max(min_x);
                    let caret_x: f32 = (text_rect.get_x() + last_w + trailing_gap)
                        .min(max_x)
                        .max(min_x);
                    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 * scale,
                        caret_y * scale,
                        (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, radius, .. }
                | DrawCommand::SharedImage { 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 inst: GpuQuadInstance = GpuQuadInstance {
                        rect: quad,
                        clip: [
                            active_clip.get_x(),
                            active_clip.get_y(),
                            active_clip.right(),
                            active_clip.bottom(),
                        ],
                        color: [1.0, 1.0, 1.0, 1.0],
                        secondary_color: [0.0; 4],
                        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: 0.0,
                        kind: GpuPrimitiveKind::TexturedQuad as u32,
                        reserved: 0,
                    };
                    Self::push_instance_coalesced(
                        batches,
                        active_batches,
                        &mut tail_state,
                        clip_entry,
                        inst,
                        &mut coalesced_merges,
                    );
                    uploaded_instances += 1;
                }
                DrawCommand::Circle {
                    center,
                    radius,
                    color,
                } => {
                    let r: f32 = radius * scale;
                    let quad: [f32; 4] = [
                        center.get_x() * scale - r,
                        center.get_y() * scale - r,
                        r * 2.0,
                        r * 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: [r; 4],
                        stroke_or_blur: 0.0,
                        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 dx: f32 = (to.get_x() - from.get_x()) * scale;
                    let dy: f32 = (to.get_y() - from.get_y()) * scale;
                    let x0: f32 = from.get_x().min(to.get_x()) * scale;
                    let y0: f32 = from.get_y().min(to.get_y()) * scale;
                    let w: f32 = dx.abs().max(width * scale);
                    let h: f32 = dy.abs().max(width * scale);
                    let quad: [f32; 4] = [x0, y0, w, h];
                    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: [
                            from.get_x() * scale,
                            from.get_y() * scale,
                            to.get_x() * scale,
                            to.get_y() * scale,
                        ],
                        stroke_or_blur: width * scale,
                        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;
                    let min_y: f32 = p0.get_y().min(p1.get_y()).min(p2.get_y()) * scale;
                    let max_x: f32 = p0.get_x().max(p1.get_x()).max(p2.get_x()) * scale;
                    let max_y: f32 = p0.get_y().max(p1.get_y()).max(p2.get_y()) * scale;
                    let quad: [f32; 4] = [
                        min_x,
                        min_y,
                        (max_x - min_x).max(1.0),
                        (max_y - min_y).max(1.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, 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 inst: GpuQuadInstance = GpuQuadInstance {
                        rect: quad,
                        clip: [
                            active_clip.get_x(),
                            active_clip.get_y(),
                            active_clip.right(),
                            active_clip.bottom(),
                        ],
                        color: tint.to_f32_array(),
                        secondary_color: [0.0; 4],
                        radii: [0.0; 4],
                        stroke_or_blur: 0.0,
                        angle_rad: 0.0,
                        kind: GpuPrimitiveKind::TexturedQuad as u32,
                        reserved: 1,
                    };
                    Self::push_instance_coalesced(
                        batches,
                        active_batches,
                        &mut tail_state,
                        clip_entry,
                        inst,
                        &mut coalesced_merges,
                    );
                    uploaded_instances += 1;
                }
            }
        }
        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 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 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))
    }

    /// Appends `instance` in strict draw order into the tail `GpuBatch` when clip-compatible, or opens the next reusable batch slot.
    ///
    /// # 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 to batch in exact back-to-front order.
    /// - `&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 scissor: Rect = clip_entry.scissor;
        let is_blur: bool = instance.kind == GpuPrimitiveKind::BackdropBlur as u32;
        let inst_unclipped: bool =
            !is_blur && Self::quad_inside_rect(instance.rect, clip_entry.safe_inner);
        let prim: GpuPrimitiveInstance =
            GpuPrimitiveInstance::from_quad_instance(&instance, 0, tail_state.layer_id);
        let count: usize = *active_batches;
        if count > 0 {
            let last: &mut GpuBatch = &mut batches[count - 1];
            if last.get_instances().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_instances().push(instance);
                    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, instance.rect);
                    return;
                }
                if !blur_boundary
                    && inst_unclipped
                    && Self::quad_inside_rect(instance.rect, last_scissor)
                {
                    last.get_mut_instances().push(instance);
                    last.get_mut_primitives().push(prim);
                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.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_instances().push(instance);
                    last.get_mut_primitives().push(prim);
                    tail_state.all_unclipped = inst_unclipped;
                    tail_state.bounds = Self::union_rect_quad(tail_state.bounds, instance.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_instances().push(instance);
            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_instances().reserve(512);
            batch.get_mut_primitives().reserve(512);
            batch.get_mut_instances().push(instance);
            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(
            instance.rect[0],
            instance.rect[1],
            instance.rect[2],
            instance.rect[3],
        );
    }
}