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
//! Draws accumulated for one submission.
//!
//! A batch is a declarative description of a scene: shared geometry plus a
//! list of draws over it. Backends are handed the whole thing rather than a
//! stream of recording calls, which lets each decide how to realize it — a
//! Vulkan backend binds pipelines only where they change, and a record-and-
//! replay backend can inspect the whole batch before touching any state.
use crate::material::ColorFilter;
use crate::{BlendMode, Error, Extent2D, Material, Result, Scissor};
/// What a draw does with the stencil buffer.
///
/// # Why the stencil holds a depth rather than a mask
///
/// The obvious encoding gives each clip a bit, which caps nesting at eight and
/// makes intersecting two clips a per-bit affair. Storing the *nesting depth*
/// instead lets a clip stack of any size fit in the same eight bits, and makes
/// the test a single comparison: content belongs to depth `d` and draws where
/// the stencil holds `d`, which is true only where every clip down to that
/// depth admitted the pixel.
///
/// It also makes undoing a clip a local operation. Because a stack unwinds in
/// the order it was built, no pixel can hold more than the depth being left, so
/// stepping back is a decrement rather than a recomputation from the remaining
/// clips.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ClipRole {
/// Draw color where the stencil already matches. Leaves the stencil alone.
#[default]
Content,
/// Narrow the clip: step the stencil forward where it matches and this draw
/// covers. Writes no color.
///
/// The geometry must be a triangulation of the clip region rather than an
/// overlapping set, since a pixel covered twice would step forward twice
/// and stop matching anything. The fill tessellator produces exactly that,
/// which is what lets this be a plain increment instead of the parity trick
/// an overlapping fan would need.
Narrow,
/// Widen the clip back: step the stencil back where it matches. Writes no
/// color.
Widen,
}
impl ClipRole {
/// Whether this role writes to the color attachment.
pub const fn writes_color(self) -> bool {
matches!(self, Self::Content)
}
/// Whether this role modifies the stencil.
pub const fn writes_stencil(self) -> bool {
!matches!(self, Self::Content)
}
}
/// The stencil state one draw needs.
///
/// `reference` is what the stencil is compared against, stated directly rather
/// than derived from a nesting depth, so the HAL needs no notion of a clip
/// stack: a narrowing draw compares against the depth it is leaving and a
/// widening draw against the one it is leaving behind, and which is which is
/// the recorder's business.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ClipState {
pub reference: u32,
pub role: ClipRole,
}
impl ClipState {
/// Content outside any clip, which needs no stencil at all.
pub const UNCLIPPED: Self = Self {
reference: 0,
role: ClipRole::Content,
};
pub const fn content(reference: u32) -> Self {
Self {
reference,
role: ClipRole::Content,
}
}
pub const fn narrow(from: u32) -> Self {
Self {
reference: from,
role: ClipRole::Narrow,
}
}
pub const fn widen(from: u32) -> Self {
Self {
reference: from,
role: ClipRole::Widen,
}
}
/// Whether this needs a stencil attachment to mean anything.
pub const fn needs_stencil(self) -> bool {
self.reference != 0 || self.role.writes_stencil()
}
}
/// One vertex: where it is, and where it reads from.
///
/// # Why every vertex carries texture coordinates
///
/// Most geometry here does not need them — a solid fill and a gradient both
/// locate themselves from the interpolated clip position. A glyph run does: a
/// run is many quads reading different parts of one atlas, and a material is
/// per draw, so coordinates carried in the paint would mean a draw per glyph.
/// Text is the highest draw-count content there is, so that is the wrong place
/// to spend.
///
/// The cost is eight bytes on every vertex, including the ones that ignore
/// them. The alternative — a second vertex format and a second pipeline for
/// text — spends more in pipeline state and in the code that has to decide
/// which of two shapes a batch is in, to save memory on the geometry that is
/// already the cheapest to store.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[repr(C)]
pub struct Vertex {
/// Homogeneous clip position: the point as the recorder produced it,
/// *before* the rasterizer divides.
///
/// `w` is one for everything an affine transform placed, which is nearly
/// everything, and the third float is what lets a transform with
/// perspective say anything at all — there is no two-component form of a
/// point that has been divided by a quantity varying across the triangle.
///
/// Carrying it undivided rather than dividing on the way here buys two
/// things beyond the mapping itself. The rasterizer clips against the plane
/// where `w` reaches zero, so geometry crossing the vanishing line is cut
/// there by the hardware instead of arriving as coordinates on both sides
/// of infinity. And every varying beside this one — texture coordinates
/// most of all — is then interpolated perspective-correctly, which is the
/// difference between a textured quad seen at an angle and the diagonal
/// seam that affine interpolation puts across it.
pub position: [f32; 3],
/// Where in a sampled texture this vertex reads, if the material samples
/// one. Zero where it does not, which costs nothing to interpolate.
pub uv: [f32; 2],
/// A color multiplied into whatever the material produced, **premultiplied**.
///
/// Opaque white for everything but a mesh a caller colored, and white is
/// the identity, so a fill pays for this in bandwidth rather than in a
/// second path. Sixteen bytes per vertex: at fifty thousand vertices a
/// frame, which is a great deal of two-dimensional geometry, that is under
/// fifty megabytes a second against a tiler already spending ten times
/// that on the framebuffer alone. A second vertex layout and a second
/// pipeline would save it and cost a permanent split in the batch model,
/// which is the wrong trade at this magnitude.
///
/// Premultiplied rather than straight because it is interpolated across a
/// triangle, and interpolating straight color between vertices whose alpha
/// differs gives a color no point on the edge actually has.
pub color: [f32; 4],
}
impl Vertex {
pub const fn new(position: [f32; 2], uv: [f32; 2]) -> Self {
Self::projected([position[0], position[1], 1.0], uv)
}
/// A vertex that samples nothing.
pub const fn at(position: [f32; 2]) -> Self {
Self::new(position, [0.0, 0.0])
}
/// A vertex whose position is already homogeneous.
///
/// The form a transform carrying perspective produces. [`Self::new`] is
/// this with a `w` of one, which is what an affine always gives, and is why
/// the ordinary constructors did not have to change when the third float
/// arrived.
pub const fn projected(position: [f32; 3], uv: [f32; 2]) -> Self {
Self {
position,
uv,
color: WHITE,
}
}
/// A homogeneous vertex that samples nothing.
pub const fn at_projected(position: [f32; 3]) -> Self {
Self::projected(position, [0.0, 0.0])
}
/// The same vertex, tinted.
///
/// `color` is premultiplied; see [`Self::color`].
pub const fn with_color(mut self, color: [f32; 4]) -> Self {
self.color = color;
self
}
}
/// The color that changes nothing when multiplied in.
const WHITE: [f32; 4] = [1.0, 1.0, 1.0, 1.0];
/// One draw within a batch.
#[derive(Debug, Clone)]
pub struct BatchDraw {
pub first_index: u32,
pub index_count: u32,
pub material: Material,
/// A function applied to the material's color before the blend.
///
/// Beside the material rather than inside it, for the same reason the
/// blend mode is: it applies to every kind of material equally and belongs
/// to none of them. It is packed into the same uniform the material is,
/// because the shader reads one block per draw.
pub filter: ColorFilter,
pub blend: BlendMode,
/// The region of the target this draw may write to.
///
/// `None` is the whole target. It is distinct from a rectangle that happens
/// to cover the target so a backend can tell "this draw was never clipped"
/// from "this draw's clip works out to everything", and skip the state
/// change in the first case without having to know the target's size.
///
/// Independent of [`Self::stencil`], and both apply. An axis-aligned clip
/// stays here even where a stencil is already in play, because a scissor is
/// exact and costs nothing while a stencil pass costs a draw.
pub clip: Option<Scissor>,
/// What this draw does with the stencil buffer.
pub stencil: ClipState,
/// How a color the caller attached to a vertex or a sprite combines with
/// what the material produced.
///
/// [`BlendMode::Modulate`] multiplies them, which is what every draw did
/// before this existed and is what a paint with no per-vertex color wants:
/// white is the identity under it. Distinct from [`Self::blend`], which is
/// how the result then reaches the target -- these two colors are both in
/// the shader, so this one needs no extension and every mode is available.
pub tint_blend: BlendMode,
/// Read the paint at this draw's texture coordinates rather than at the
/// position of the fragment.
///
/// A property of the geometry rather than of the material, which is why it
/// is here: a mesh that states a coordinate per vertex has said where each
/// one sits in the paint's space, and there is nothing left to derive. An
/// image already worked this way and had its own material for it; this is
/// what lets a gradient or a caller's program do the same.
///
/// False everywhere else, and it costs those draws nothing: the flag lands
/// in a slot no material that could set it uses, and the shader's select
/// is one instruction on a value it has already computed.
pub paint_at_texture_coords: bool,
}
impl BatchDraw {
/// Whether this draw may be moved ahead of earlier draws it covers.
///
/// A draw that answers yes replaces every sample it touches, so nothing
/// underneath it can show through and the painter's-order guarantee this
/// batch otherwise relies on does not apply to it. That is what makes an
/// opaque reordering possible: `docs/non-parity.md` 21 has the measurement,
/// and on both boards here the covered part of a frame's background is
/// around forty per cent of the frame.
///
/// **Conservative on purpose, and every condition below is load-bearing.** A
/// wrong yes is not a slow frame, it is a wrong picture -- a background
/// showing through where it should not, or showing when it should not -- so
/// each test is for a property that can be read off the draw rather than
/// reasoned about, and anything this cannot prove answers no.
///
/// - **`Material::Solid` with an opaque alpha, and nothing else.** A solid
/// fill takes its coverage from the rasterizer, so a sample is either
/// inside the geometry or outside it and there is no partial result. The
/// analytic materials are the case this exists to exclude:
/// `RoundedRect`, `Ellipse` and `RoundedRectBlur` compute coverage in the
/// shader and blend it, so an *opaque* color still leaves a soft edge, and
/// writing depth there would hide the background behind a half-covered
/// pixel. Gradients and images could be opaque and are refused anyway:
/// proving it means reading every stop or every texel.
/// - **Alpha at or above one.** Premultiplied and straight color agree
/// there, so the form the material carries does not have to be known.
/// - **`Src` or `SrcOver`.** Both put an opaque source through unchanged.
/// Every other mode reads the destination, which is the thing being
/// reordered away.
/// - **No color filter.** A matrix or a blend filter can take alpha below
/// one after the material produced it.
/// - **`Modulate` tinting.** It is the identity against the white a solid
/// fill carries; another mode is a second color this cannot see.
/// - **Every vertex carrying white.** A vertex color multiplies the
/// material, so a translucent one makes a translucent draw out of an
/// opaque material -- and `Material::Solid` is exactly the pairing
/// `draw_vertices` produces for a caller's mesh. This is why the vertex
/// buffer is a parameter: the material cannot answer it, and the draw
/// does not hold it. Refused for any non-white color rather than only a
/// translucent one, since a colored-but-opaque vertex still has to be
/// read to know that, and it costs nothing to say no.
/// - **Unclipped.** A `Narrow` or `Widen` draw writes the stencil rather
/// than color and is sequencing, not content. A clipped `Content` draw
/// writes color but depends on stencil state that the draws around it
/// establish, so moving it past them would change what it is clipped to.
///
/// Antialiasing does not appear here, and that is the point rather than an
/// omission. It is multisampling in this renderer -- `Canvas::pass_samples`
/// raises the whole pass's sample count and no draw blends its own coverage
/// -- so an opaque solid fill is binary at every sample whether the pass is
/// multisampled or not, which is exactly the case a depth test is built for.
/// A renderer that antialiased by blending coverage could not use this
/// predicate at all.
/// The whole pixels this draw certainly covers, where that is knowable exactly.
///
/// `None` unless the geometry is a quad standing on its own bounding box: four
/// vertices at the four corners, six indices forming two triangles that share the
/// quad's diagonal. That is what an axis-aligned rectangle fill tessellates to, and
/// it is the one shape whose covered area is its bounding box rather than something
/// strictly inside it. Everything else -- a rotated rectangle, a path, a stroke, a
/// glyph run -- is refused rather than approximated, because the answer is used to
/// stop drawing something underneath and a rectangle too large leaves a hole in the
/// frame.
///
/// Every test here is discrete, with no tolerance anywhere. A quad one part in ten
/// thousand short of its bounding box would pass an area comparison and leave a
/// sub-pixel notch, and at four samples a notch is a visible seam. Exact corners or
/// nothing.
///
/// Two triangles sharing a *side* rather than the diagonal are refused too. They
/// have six indices over four vertices and cover half the box, so nothing short of
/// looking at which pair is shared tells them apart.
///
/// The positions are homogeneous clip coordinates, so this converts. `w` must be
/// exactly one on all four vertices, which refuses perspective rather than dividing
/// by a quantity that varies across the quad, and the normalized range maps onto the
/// target with y running downward -- the orientation [`Scissor`] fixes and that both
/// backends already agree on. [`Scissor::covered_device_bounds`] then rounds inward.
pub fn covered(
&self,
vertices: &[Vertex],
indices: &[u32],
extent: Extent2D,
) -> Option<Scissor> {
if self.index_count != 6 {
return None;
}
let first = self.first_index as usize;
let six = indices.get(first..first.checked_add(6)?)?;
let (left, right) = (&six[..3], &six[3..]);
// Each triangle names three distinct vertices, or it has no area.
for tri in [left, right] {
if tri[0] == tri[1] || tri[1] == tri[2] || tri[0] == tri[2] {
return None;
}
}
// Two shared vertices, which is what sharing an edge means.
let shared: Vec<u32> = left.iter().copied().filter(|i| right.contains(i)).collect();
if shared.len() != 2 {
return None;
}
let mut distinct: Vec<u32> = Vec::with_capacity(4);
for &i in six {
if !distinct.contains(&i) {
distinct.push(i);
}
}
if distinct.len() != 4 {
return None;
}
let at = |index: u32| -> Option<[f32; 2]> {
let v = vertices.get(index as usize)?;
// Affine only. A perspective quad's covered region is not its bounding box.
(v.position[2] == 1.0).then_some([v.position[0], v.position[1]])
};
let mut corners = [[0.0f32; 2]; 4];
for (slot, &index) in corners.iter_mut().zip(&distinct) {
*slot = at(index)?;
}
let fold = |f: fn(f32, f32) -> f32, axis: usize, seed: f32| {
corners.iter().map(|c| c[axis]).fold(seed, f)
};
let min_x = fold(f32::min, 0, f32::INFINITY);
let max_x = fold(f32::max, 0, f32::NEG_INFINITY);
let min_y = fold(f32::min, 1, f32::INFINITY);
let max_y = fold(f32::max, 1, f32::NEG_INFINITY);
// Every corner at one extreme in each axis, and all four combinations present.
// A quad with three corners on its box and the fourth inside passes neither.
let quadrant = |c: [f32; 2]| -> Option<usize> {
let east = if c[0] == min_x {
false
} else if c[0] == max_x {
true
} else {
return None;
};
let south = if c[1] == min_y {
false
} else if c[1] == max_y {
true
} else {
return None;
};
Some(usize::from(east) + 2 * usize::from(south))
};
let mut seen = [false; 4];
for &c in &corners {
seen[quadrant(c)?] = true;
}
if !seen.iter().all(|&s| s) {
return None;
}
// The shared pair must be opposite corners. Sharing a side leaves both triangles
// on one half of the quad.
let a = quadrant(at(shared[0])?)?;
let b = quadrant(at(shared[1])?)?;
if a + b != 3 {
return None;
}
// `viewport_projection` is `x * 2/w - 1` across and `1 - y * 2/h` down, so clip
// space runs left to right with the target but *bottom to top against it*: a
// clip y of +1 is the target's first row. Inverting that mapping swaps which end
// is the minimum, and getting it backwards is not a subtle failure -- it mirrors
// every culled region vertically, which showed as a card's shadow landing above
// the card instead of below it.
let across = |v: f32| (v + 1.0) * 0.5 * extent.width as f32;
let down = |v: f32| (1.0 - v) * 0.5 * extent.height as f32;
let min = [across(min_x), down(max_y)];
let max = [across(max_x), down(min_y)];
let covered = Scissor::covered_device_bounds(min, max, extent);
Some(match self.clip {
Some(clip) => covered.intersect(clip),
None => covered,
})
}
/// Whether writing this draw's pixels twice gives what writing them once gives.
///
/// The condition for splitting a draw into several, and it is not the same question
/// as [`Self::occludes`]. That one asks whether a draw hides what is under it; this
/// asks whether it is safe to draw *overlapping* copies of it -- which matters
/// because a driver may write a pixel outside the scissor it was given.
///
/// **Measured, not hypothetical.** lavapipe on Mesa 25.2.8 and 15.0.6 writes the
/// pixel to the left of a scissor at half coverage when the pass is multisampled;
/// 26.1.7, RADV and PanVK are clean. `public_api.rs` probes for it. Where it happens,
/// two pieces of one draw overlap by a column -- and a translucent draw blends there
/// twice, which reads 90 against 121 on a half-transparent wash under an opaque bar.
/// An opaque one writes the same color twice and cannot tell.
///
/// So a draw splits only where a second write is a no-op: `Src` replaces whatever the
/// alpha, and `SrcOver` replaces only where the source is opaque -- which means the
/// material, the absence of a color filter, an identity tint, and the vertex colors
/// the tint multiplies in, all four.
pub fn splits_safely(&self, vertices: &[Vertex], indices: &[u32]) -> bool {
if self.filter != ColorFilter::None || self.tint_blend != BlendMode::Modulate {
return false;
}
// Premultiplied, and interpolated across the triangle -- so a single translucent
// corner makes part of the draw translucent however opaque its material is.
let first = self.first_index as usize;
let count = self.index_count as usize;
let Some(range) = indices.get(first..first.saturating_add(count)) else {
return false;
};
for &index in range {
match vertices.get(index as usize) {
Some(v) if v.color[3] >= 1.0 => {}
_ => return false,
}
}
match self.blend {
BlendMode::Src => true,
// `VertexGradient` shades opaque white, and the tint above is
// `Modulate`, so the result's alpha *is* the vertex alpha -- which
// the loop has just checked. `Material::is_opaque` cannot say so:
// it answers about the material alone, and the colors are not
// there. Without this a vertex-interpolated gradient is never
// split, so the wash under an interface paints every pixel the
// panels cover.
BlendMode::SrcOver => {
self.material.is_opaque() || matches!(self.material, Material::VertexGradient)
}
_ => false,
}
}
pub fn occludes(&self, vertices: &[Vertex], indices: &[u32]) -> bool {
self.stencil == ClipState::UNCLIPPED
&& matches!(self.blend, BlendMode::Src | BlendMode::SrcOver)
&& self.filter == ColorFilter::None
&& self.tint_blend == BlendMode::Modulate
&& !self.paint_at_texture_coords
&& matches!(self.material, Material::Solid(color) if color[3] >= 1.0)
// Last, because it is the only test here that reads a buffer.
&& self.vertices_are_white(vertices, indices)
}
/// Whether every vertex this draw names carries white, the identity for a
/// color that multiplies the material.
///
/// A draw naming a vertex or an index that is not there answers no. That
/// cannot happen in a batch this crate built, and a predicate whose wrong
/// answer is a wrong picture does not get to assume it.
fn vertices_are_white(&self, vertices: &[Vertex], indices: &[u32]) -> bool {
let first = self.first_index as usize;
let Some(end) = first.checked_add(self.index_count as usize) else {
return false;
};
let Some(range) = indices.get(first..end) else {
return false;
};
range
.iter()
.all(|&i| vertices.get(i as usize).is_some_and(|v| v.color == WHITE))
}
/// The uniform block this draw's shader reads.
///
/// The material and the filter are packed together because the shader
/// takes one block per draw, and separately here because they are separate
/// things: a filter applies to any material, and a material knows nothing
/// about being filtered.
/// `target` is the format this draw is about to be written into, which
/// only the backend knows: a recording is built without one, and the same
/// recording is drawn into an eight-bit surface and a float one. It decides
/// the dither, and nothing else here.
pub fn to_uniform(&self, target: crate::PixelFormat) -> [f32; crate::MATERIAL_FLOATS] {
let mut out = self.material.to_uniform();
self.filter.pack_into(&mut out);
out[crate::material::layout::FILTER_PARAMS + 1] = self.tint_blend.code();
if self.paint_at_texture_coords {
// `geometry.x`, which no gradient writes. See the field's own note
// and the `paint_space` comment in the shader.
out[crate::material::layout::GEOMETRY] = 1.0;
}
let dither = crate::material::layout::DITHER;
// Upstream's rate exactly: `kDitherRate` is 1/64 and is added to the
// premultiplied color whatever the target is. That is a single constant
// there because its values are encoded, so a quantization step is a
// flat 1/255 wherever it stands -- and now for the same reason it is a
// single constant here.
//
// Still zero for a target with no quantum to bridge. Half's precision
// is relative, so there is no step to straddle and upstream's constant
// would be noise added to a surface that had none.
//
// Zero for a material with no band to break, which is every one but a
// gradient. That test was the shader's and is here now: it tested the
// material kind, so a second route to the same picture under another
// kind stopped dithering without saying so.
out[dither] = if self.material.dithers() && target.quantization_step() > 0.0 {
1.0 / 64.0
} else {
0.0
};
out
}
}
/// Geometry and paint for a sequence of draws sharing one target.
///
/// Draws are kept in submission order rather than sorted by pipeline. Sorting
/// would cut pipeline binds, but 2D drawing is painter's-algorithm ordered:
/// reordering two overlapping draws changes which one ends up on top. Deciding
/// when a reorder is safe needs either overlap analysis or a depth buffer, and
/// that belongs to the layer that knows what the draws represent.
#[derive(Debug, Default, Clone)]
pub struct Batch {
vertices: Vec<Vertex>,
indices: Vec<u32>,
draws: Vec<BatchDraw>,
}
impl Batch {
pub fn new() -> Self {
Self::default()
}
/// Append a draw covering the whole target.
///
/// Indices are relative to `vertices` and are rebased onto the batch's
/// shared buffer, so a caller need not know what came before it.
pub fn push(
&mut self,
vertices: &[[f32; 2]],
indices: &[u32],
material: Material,
blend: BlendMode,
) -> Result<()> {
self.push_clipped(vertices, indices, material, blend, None)
}
/// Append a draw confined to a region of the target.
///
/// A separate entry point rather than an extra parameter on [`Self::push`]:
/// most draws are unclipped, and threading `None` through every call site
/// makes the ones that do carry a clip harder to pick out, not easier.
///
/// An empty scissor drops the draw. Recording something that provably
/// writes no pixel would cost a pipeline bind and a draw call to produce
/// the same target, and a clip stack that has narrowed to nothing is a
/// normal state for a scrolled-away subtree rather than an error.
pub fn push_clipped(
&mut self,
vertices: &[[f32; 2]],
indices: &[u32],
material: Material,
blend: BlendMode,
clip: Option<Scissor>,
) -> Result<()> {
self.push_with(
vertices,
indices,
material,
ColorFilter::None,
blend,
clip,
ClipState::UNCLIPPED,
)
}
/// Append a draw with an explicit stencil role.
///
/// The general form the other two delegate to. A caller reaches for this
/// only when building or unwinding a clip, or when drawing content inside
/// one; everything else is confined by a scissor or not confined at all.
#[allow(clippy::too_many_arguments)]
pub fn push_with(
&mut self,
positions: &[[f32; 2]],
indices: &[u32],
material: Material,
filter: ColorFilter,
blend: BlendMode,
clip: Option<Scissor>,
stencil: ClipState,
) -> Result<()> {
// Tessellated geometry has no texture coordinates of its own, and the
// materials it carries do not read them.
let vertices: Vec<Vertex> = positions.iter().copied().map(Vertex::at).collect();
self.push_mesh(&vertices, indices, material, filter, blend, clip, stencil)
}
/// Append a draw whose vertices carry texture coordinates.
///
/// The form a glyph run takes: one draw over many quads, each reading a
/// different part of the same atlas.
#[allow(clippy::too_many_arguments)]
pub fn push_mesh(
&mut self,
vertices: &[Vertex],
indices: &[u32],
material: Material,
filter: ColorFilter,
blend: BlendMode,
clip: Option<Scissor>,
stencil: ClipState,
) -> Result<()> {
self.push_mesh_tinted(
vertices,
indices,
material,
filter,
blend,
clip,
stencil,
BlendMode::Modulate,
false,
)
}
/// Append a mesh, saying how its vertex colors combine with the material.
///
/// Separate from [`Self::push_mesh`] rather than an extra parameter on it,
/// for the reason [`Self::push_clipped`] is separate: the mode is
/// `Modulate` for everything that does not ask, white being the identity
/// under it, and threading a parameter through every call site to say so
/// would be noise at all of them and a decision at none.
#[allow(clippy::too_many_arguments)]
pub fn push_mesh_tinted(
&mut self,
vertices: &[Vertex],
indices: &[u32],
material: Material,
filter: ColorFilter,
blend: BlendMode,
clip: Option<Scissor>,
stencil: ClipState,
tint_blend: BlendMode,
paint_at_texture_coords: bool,
) -> Result<()> {
if clip.is_some_and(Scissor::is_empty) {
return Ok(());
}
if indices.len() % 3 != 0 {
return Err(Error::Unsupported("index count is not a whole triangle"));
}
if let Some(&max) = indices.iter().max() {
if max as usize >= vertices.len() {
return Err(Error::Backend {
backend: "vulkan",
detail: format!(
"index {max} addresses past the {} vertices supplied",
vertices.len()
),
});
}
}
if indices.is_empty() {
return Ok(());
}
let base = u32::try_from(self.vertices.len()).map_err(|_| Error::LimitExceeded {
what: "batch vertex count",
requested: self.vertices.len() as u64,
limit: u32::MAX as u64,
})?;
let first_index = self.indices.len() as u32;
self.vertices.extend_from_slice(vertices);
self.indices.extend(indices.iter().map(|i| i + base));
// A draw that differs from the one before it in nothing a backend can
// set is not a second draw. Its indices were just appended to the same
// buffer, so extending the previous range covers both, and the
// triangles are rasterized in the same order either way -- which is
// what makes this safe under painter's-algorithm ordering, where two
// overlapping shapes must not trade places.
//
// Adjacent only, never sorted. Reordering to create more of these is a
// different decision with a different safety argument, and this one
// needs none: the sequence is untouched.
if let Some(last) = self.draws.last_mut() {
if last.first_index + last.index_count == first_index
&& last.material == material
&& last.filter == filter
&& last.blend == blend
&& last.clip == clip
&& last.stencil == stencil
&& last.tint_blend == tint_blend
&& last.paint_at_texture_coords == paint_at_texture_coords
{
last.index_count += indices.len() as u32;
return Ok(());
}
}
self.draws.push(BatchDraw {
filter,
first_index,
index_count: indices.len() as u32,
material,
blend,
clip,
stencil,
tint_blend,
paint_at_texture_coords,
});
Ok(())
}
/// Drop the contents but keep the allocations, for reuse next frame.
pub fn clear(&mut self) {
self.vertices.clear();
self.indices.clear();
self.draws.clear();
}
pub fn draw_count(&self) -> usize {
self.draws.len()
}
pub fn is_empty(&self) -> bool {
self.draws.is_empty()
}
/// Whether recording this needs a stencil attachment.
///
/// Derived from the draws rather than declared alongside them, so a batch
/// cannot ask for a clip and forget to say it needs somewhere to put it.
/// Most batches clip nothing, and those pay for no attachment.
pub fn uses_stencil(&self) -> bool {
self.draws.iter().any(|draw| draw.stencil.needs_stencil())
}
/// The deepest clip stack an eight-bit stencil can distinguish.
///
/// Eight bits is the only stencil depth every device is required to offer,
/// on either graphics API, so this is the portable limit rather than any
/// one device's.
pub const MAX_CLIP_DEPTH: u32 = 255;
/// Refuse a batch whose clip stack is deeper than a stencil can hold.
///
/// Here rather than in each backend because the limit is a property of the
/// stencil format both are required to offer, and the failure it prevents
/// is one neither can detect afterwards: past the limit the value wraps or
/// saturates, and either way a later test for a depth that no longer fits
/// admits every pixel the clip was meant to exclude. Nothing about that
/// looks like an error -- it draws content the caller clipped away.
///
/// It was in one backend and not the other, so the same recording was
/// refused on Vulkan and silently rendered wrong on GLES.
pub fn check_clip_depth(&self) -> Result<()> {
let depth = self.max_clip_depth();
if depth > Self::MAX_CLIP_DEPTH {
return Err(Error::LimitExceeded {
what: "clip nesting depth",
requested: depth as u64,
limit: Self::MAX_CLIP_DEPTH as u64,
});
}
Ok(())
}
/// The largest stencil value this batch can produce.
pub fn max_clip_depth(&self) -> u32 {
self.draws
.iter()
.map(|draw| match draw.stencil.role {
ClipRole::Narrow => draw.stencil.reference + 1,
_ => draw.stencil.reference,
})
.max()
.unwrap_or(0)
}
/// The texture slots this batch samples, in ascending order without
/// repeats.
///
/// A backend uses this to size its bindings before recording, and to check
/// the table it was given covers what the draws ask for.
pub fn texture_slots(&self) -> Vec<u32> {
let mut slots: Vec<u32> = self
.draws
.iter()
.flat_map(|draw| draw.material.texture_slots())
.flatten()
.collect();
slots.sort_unstable();
slots.dedup();
slots
}
/// How many times a pipeline will be bound when this batch is recorded.
///
/// Consecutive draws sharing a blend mode reuse the bound pipeline, so this
/// counts transitions rather than draws.
pub fn pipeline_binds(&self) -> usize {
let mut binds = 0;
let mut current: Option<BlendMode> = None;
for draw in &self.draws {
if current != Some(draw.blend) {
binds += 1;
current = Some(draw.blend);
}
}
binds
}
}
impl Batch {
/// Shared vertex buffer, positions in clip space.
/// Move every scissor into a target whose origin moved by `(dx, dy)`.
///
/// For a layer whose target was narrowed after its draws were recorded.
/// The geometry is left alone -- it is in clip space and the pass's
/// viewport is what places it -- but a scissor is in target pixels, so it
/// is the one recorded thing the move does reach.
pub fn rebase_scissors(&mut self, dx: u32, dy: u32, extent: crate::Extent2D) {
for draw in &mut self.draws {
if let Some(clip) = draw.clip {
draw.clip = Some(clip.shifted(dx, dy, extent));
}
}
}
pub fn vertices(&self) -> &[Vertex] {
&self.vertices
}
/// Shared index buffer, already rebased onto [`Batch::vertices`].
pub fn indices(&self) -> &[u32] {
&self.indices
}
/// The draws, in submission order.
pub fn draws(&self) -> &[BatchDraw] {
&self.draws
}
/// Stop each draw writing pixels a later opaque draw will overwrite.
///
/// Returns how many draws were narrowed or dropped, which is what a test asserts
/// on -- a pass that quietly did nothing would otherwise look like a pass.
///
/// # Why this is not reordering
///
/// Draw order is untouched. Each draw is confined, by scissor, to the pixels no
/// later opaque draw replaces. `docs/non-parity.md` 21 wanted a depth buffer to
/// reorder opaque draws and `docs/on-a-board.md` records why that is closed here:
/// at four samples the attachment costs four times the pass on V3D, and the frame
/// worth reordering is four samples. A scissor costs nothing and needs no
/// attachment.
///
/// It is also pixel-identical rather than approximately right. For draws `i` before
/// `j`, if `j` replaces every sample of a pixel then nothing `i` wrote there can
/// reach the frame -- including by way of something between them that blended
/// against it, since that result is replaced too. [`BatchDraw::occludes`] is
/// exactly the "replaces every sample it touches" predicate, and
/// [`BatchDraw::covered`] is where it does so.
///
/// # What limits it
///
/// Only the occluder needs known coverage. The draw being narrowed needs nothing at
/// all, because a scissor restricts any geometry -- which is what makes this worth
/// doing, since the thing being saved is usually a gradient or an image and neither
/// is a shape this could reason about.
///
/// Two caps keep the work bounded on a batch that is nothing like a frame of
/// interface. `MAX_BLOCKERS` is how many occluders are carried at once, and
/// [`crate::occlusion::MAX_PIECES`] is how many rectangles a remainder may need before the
/// draw is left alone. Both failures are safe: drawing more than necessary is slow,
/// never wrong.
pub fn cull_occluded(&mut self, extent: Extent2D) -> usize {
/// Occluders carried while walking back through the draws.
///
/// The walk is from the front of the frame backwards, so these are the draws
/// nearest the viewer -- the ones most likely to be hiding something. Sixteen
/// bounds the remainder arithmetic, which is quadratic in this count.
const MAX_BLOCKERS: usize = 16;
if self.draws.len() < 2 || extent.width == 0 || extent.height == 0 {
return 0;
}
let whole = Scissor::covering(extent);
let mut blockers: Vec<Scissor> = Vec::with_capacity(MAX_BLOCKERS);
let mut rewritten = 0usize;
// Built back to front and reversed once, rather than inserted into.
let mut out: Vec<BatchDraw> = Vec::with_capacity(self.draws.len());
for index in (0..self.draws.len()).rev() {
let draw = self.draws[index].clone();
let covered = draw
.occludes(&self.vertices, &self.indices)
.then(|| draw.covered(&self.vertices, &self.indices, extent))
.flatten();
// A draw that writes the stencil is sequencing rather than content: its
// effect is not confined to the pixels it colors, so narrowing its scissor
// would change which pixels a *later* clipped draw is clipped to. Left
// alone, and it cannot be an occluder either -- `occludes` already refuses
// anything but `UNCLIPPED`.
// A draw whose shading reads screen-space derivatives cannot be split by
// scissor without changing its edge -- see
// `Material::needs_screen_derivatives`, which has the measurement. This is
// where the pass stops being free, and it is why the prize survives anyway:
// the gradient that costs the frame is derivative-free and the analytic
// shapes that are not are cheap.
if blockers.is_empty()
|| draw.stencil.role.writes_stencil()
|| draw.material.needs_screen_derivatives()
{
out.push(draw);
} else {
let own = draw.clip.unwrap_or(whole);
match crate::occlusion::remainder(own, &blockers) {
// Nothing of this draw survives, so it does not need drawing.
Some(pieces) if pieces.is_empty() => rewritten += 1,
// One piece covering what it already had: leave the draw exactly as
// it was, clip included. A draw that was never clipped keeps saying
// so, which is a distinction `BatchDraw::clip` documents.
Some(pieces) if pieces.len() == 1 && pieces[0] == own => out.push(draw),
// More than one piece means overlapping writes on a driver that
// does not honor a scissor exactly, so the draw has to survive
// being written twice. One piece cannot overlap anything.
Some(pieces)
if pieces.len() > 1
&& !draw.splits_safely(&self.vertices, &self.indices) =>
{
out.push(draw);
}
Some(pieces) => {
rewritten += 1;
for piece in pieces {
out.push(BatchDraw {
clip: Some(piece),
..draw.clone()
});
}
}
// Past the cap. Left alone, which is always correct.
None => out.push(draw),
}
}
if let Some(area) = covered {
if !area.is_empty() && blockers.len() < MAX_BLOCKERS {
blockers.push(area);
}
}
}
out.reverse();
self.draws = out;
rewritten
}
}
#[cfg(test)]
mod tests {
use super::*;
const TRI: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
/// A draw carrying just the material, since the dither depends on nothing
/// else about it.
fn draw_of(material: Material) -> BatchDraw {
BatchDraw {
first_index: 0,
index_count: 3,
material,
filter: ColorFilter::None,
blend: BlendMode::SrcOver,
clip: None,
stencil: ClipState::UNCLIPPED,
tint_blend: BlendMode::Modulate,
paint_at_texture_coords: false,
}
}
fn wash() -> crate::Material {
crate::Material::LinearGradient {
axis: [1.0, 0.0],
to_local: [0.0; 12],
stops: vec![
crate::Stop::new([0.0, 0.0, 0.0, 1.0], 0.0),
crate::Stop::new([1.0, 1.0, 1.0, 1.0], 1.0),
],
ramp: None,
tile: crate::TileMode::Clamp,
}
}
/// The dither amplitude follows the material, not the shader's reading of
/// the material's kind.
///
/// This is the contract that replaced a branch in `solid.wgsl`. The shader
/// could only ask what kind a draw was, so a second route to a gradient
/// under another kind stopped dithering silently -- which is how the
/// reverted fast-gradient attempt lost it. See `Material::dithers` and §19
/// of `docs/non-parity.md`.
#[test]
fn only_a_material_that_asks_for_a_dither_gets_an_amplitude() {
let dither = crate::material::layout::DITHER;
let eight_bit = crate::PixelFormat::Rgba8Unorm;
let gradient = draw_of(wash()).to_uniform(eight_bit);
assert!(
gradient[dither] > 0.0,
"a gradient on an eight-bit target got no dither"
);
let solid = draw_of(Material::Solid([1.0, 0.0, 0.0, 1.0])).to_uniform(eight_bit);
assert_eq!(
solid[dither], 0.0,
"a solid fill was dithered, which adds noise to a flat color"
);
}
/// And a target with no quantum to bridge gets none whatever the material
/// asks for: half's precision is relative, so there is no step to straddle.
#[test]
fn a_float_target_gets_no_dither_even_for_a_gradient() {
let dither = crate::material::layout::DITHER;
let packed = draw_of(wash()).to_uniform(crate::PixelFormat::Rgba16Float);
assert_eq!(packed[dither], 0.0, "a float target was dithered");
}
#[test]
fn indices_are_rebased_onto_the_shared_buffer() {
let mut batch = Batch::new();
// Two colors, so the draws do not merge and the second one's own
// range is visible. What is being checked is the rebasing, which a
// merged pair would hide behind a single range covering both.
batch
.push(&TRI, &[0, 1, 2], Material::solid([1.0; 4]), BlendMode::Src)
.unwrap();
batch
.push(&TRI, &[0, 1, 2], Material::solid([0.5; 4]), BlendMode::Src)
.unwrap();
// The second draw's indices must point at its own vertices, not the
// first draw's, or both draws render the same triangle.
assert_eq!(batch.indices, vec![0, 1, 2, 3, 4, 5]);
assert_eq!(batch.vertices.len(), 6);
assert_eq!(batch.draws[1].first_index, 3);
assert_eq!(batch.draw_count(), 2);
}
#[test]
fn a_draw_that_differs_from_the_one_before_it_in_nothing_is_not_a_second_draw() {
let mut batch = Batch::new();
for _ in 0..4 {
batch
.push(&TRI, &[0, 1, 2], Material::solid([1.0; 4]), BlendMode::Src)
.unwrap();
}
assert_eq!(batch.draw_count(), 1, "four alike draws should be one");
// All four triangles are still there, and still in order: merging
// changes how many times a backend is asked to draw, not what it
// draws.
assert_eq!(batch.indices, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
assert_eq!(batch.draws[0].index_count, 12);
// A change in any one thing a backend sets ends the run.
batch
.push(
&TRI,
&[0, 1, 2],
Material::solid([1.0; 4]),
BlendMode::SrcOver,
)
.unwrap();
assert_eq!(batch.draw_count(), 2);
}
#[test]
fn pipeline_binds_count_transitions_not_draws() {
let mut batch = Batch::new();
// A different color each time, so no two draws merge and the count
// this is about -- pipeline binds against draws -- stays a real
// distinction rather than one merging has already collapsed.
for (i, blend) in [
BlendMode::Src,
BlendMode::Src,
BlendMode::SrcOver,
BlendMode::SrcOver,
BlendMode::Src,
]
.into_iter()
.enumerate()
{
let shade = i as f32 / 8.0;
batch
.push(&TRI, &[0, 1, 2], Material::solid([shade; 4]), blend)
.unwrap();
}
// Five draws, three runs of like pipelines.
assert_eq!(batch.draw_count(), 5);
assert_eq!(batch.pipeline_binds(), 3);
}
#[test]
fn an_empty_draw_adds_nothing() {
let mut batch = Batch::new();
batch
.push(&[], &[], Material::solid([1.0; 4]), BlendMode::Src)
.unwrap();
assert!(batch.is_empty());
assert_eq!(batch.draw_count(), 0);
}
#[test]
fn malformed_geometry_is_refused_where_it_is_pushed() {
let mut batch = Batch::new();
// Catching this at push means the caller learns which draw was wrong,
// rather than a whole batch failing later at submission.
assert!(batch
.push(
&[[0.0, 0.0]],
&[0, 1, 2],
Material::solid([1.0; 4]),
BlendMode::Src
)
.is_err());
assert!(batch
.push(
&[[0.0, 0.0]],
&[0, 0],
Material::solid([1.0; 4]),
BlendMode::Src
)
.is_err());
assert!(batch.is_empty(), "a refused draw must leave no residue");
}
#[test]
fn clearing_keeps_the_batch_reusable() {
let mut batch = Batch::new();
batch
.push(&TRI, &[0, 1, 2], Material::solid([1.0; 4]), BlendMode::Src)
.unwrap();
batch.clear();
assert!(batch.is_empty());
batch
.push(&TRI, &[0, 1, 2], Material::solid([1.0; 4]), BlendMode::Src)
.unwrap();
// Rebasing must start from zero again rather than continuing from the
// cleared contents.
assert_eq!(batch.indices, vec![0, 1, 2]);
}
/// Both backends describe this struct to their own API by asking it where
/// its fields are, so what they agree on is whatever this says. Pinning it
/// means a reordering shows up here, once, rather than as geometry that
/// reads its color out of its position on both backends identically.
#[test]
fn the_vertex_layout_is_what_both_backends_describe() {
use std::mem::{offset_of, size_of};
assert_eq!(size_of::<Vertex>(), 36);
assert_eq!(offset_of!(Vertex, position), 0);
assert_eq!(offset_of!(Vertex, uv), 12);
assert_eq!(offset_of!(Vertex, color), 20);
}
/// The property that let the third float arrive without touching a caller.
#[test]
fn an_ordinary_vertex_carries_a_w_of_one() {
assert_eq!(Vertex::at([3.0, 4.0]).position, [3.0, 4.0, 1.0]);
assert_eq!(
Vertex::new([3.0, 4.0], [0.5, 0.5]).position,
[3.0, 4.0, 1.0]
);
assert_eq!(
Vertex::at_projected([3.0, 4.0, 2.0]).position,
[3.0, 4.0, 2.0]
);
}
}
#[cfg(test)]
mod occlusion {
use super::*;
use crate::material::ToLocal;
const TRI: [[f32; 2]; 3] = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
fn one(material: Material, blend: BlendMode) -> BatchDraw {
let mut batch = Batch::new();
batch.push(&TRI, &[0, 1, 2], material, blend).unwrap();
batch.draws().first().expect("one draw").clone()
}
/// The buffers `one` builds: three vertices carrying white, indexed in
/// order. `occludes` reads them, so every call here needs a pair, and these
/// are the ones a plain `push` produces.
const WHITE_TRI_INDICES: [u32; 3] = [0, 1, 2];
fn white_tri() -> Vec<Vertex> {
vec![Vertex::at([0.0, 0.0]); 3]
}
/// A vertex color multiplies the material, so a translucent one makes a
/// translucent draw out of an opaque `Material::Solid` -- which is exactly
/// the pairing `draw_vertices` builds for a caller's mesh.
///
/// This was reachable from the public API and wrong by 128 of 255: an
/// indexed quad with translucent vertex colors passed both `occludes` and
/// `covered`, so the draw beneath it was culled and showed through nothing.
/// §19 of `docs/non-parity.md` predicted the unsoundness as a blocker for
/// upstream's vertex-interpolated gradient; it was already live.
#[test]
fn a_translucent_vertex_color_is_not_an_occluder() {
let mut batch = Batch::new();
batch
.push(
&TRI,
&[0, 1, 2],
Material::solid([1.0; 4]),
BlendMode::SrcOver,
)
.unwrap();
let draw = batch.draws().first().expect("one draw").clone();
let opaque = vec![Vertex::at([0.0, 0.0]); 3];
assert!(
draw.occludes(&opaque, &WHITE_TRI_INDICES),
"white vertices leave an opaque solid fill an occluder"
);
let translucent = vec![Vertex::at([0.0, 0.0]).with_color([1.0, 0.0, 0.0, 0.25]); 3];
assert!(
!draw.occludes(&translucent, &WHITE_TRI_INDICES),
"a translucent vertex color was called an occluder"
);
// Opaque but colored is refused too: knowing it is opaque means reading
// it, and the predicate says no to anything it has to reason about.
let tinted = vec![Vertex::at([0.0, 0.0]).with_color([1.0, 0.0, 0.0, 1.0]); 3];
assert!(
!draw.occludes(&tinted, &WHITE_TRI_INDICES),
"a colored vertex was called an occluder"
);
}
/// An interpolated gradient splits when its vertex alphas are opaque, and
/// not otherwise.
///
/// `Material::is_opaque` answers no for `VertexGradient` -- the colors are
/// not in the material -- so without the vertex test above it this draw
/// would never be confined by culling, and a wash under an interface would
/// paint every pixel the panels over it cover. The bench notices:
/// `the_stacked_frame_overdraws_by_what_its_prose_claims` reads 131 draws
/// with this and 127 without.
#[test]
fn an_interpolated_gradient_splits_when_its_vertices_are_opaque() {
let mut batch = Batch::new();
batch
.push(
&TRI,
&[0, 1, 2],
Material::VertexGradient,
BlendMode::SrcOver,
)
.unwrap();
let draw = batch.draws().first().expect("one draw").clone();
let opaque = vec![Vertex::at([0.0, 0.0]).with_color([0.2, 0.4, 0.8, 1.0]); 3];
assert!(
draw.splits_safely(&opaque, &WHITE_TRI_INDICES),
"every vertex alpha is one, so the result is opaque"
);
let translucent = vec![Vertex::at([0.0, 0.0]).with_color([0.2, 0.4, 0.8, 0.5]); 3];
assert!(
!draw.splits_safely(&translucent, &WHITE_TRI_INDICES),
"a translucent vertex makes part of the draw translucent"
);
// Still not an *occluder*: `occludes` admits only `Material::Solid`,
// and this one's color is not in the material.
assert!(!draw.occludes(&opaque, &WHITE_TRI_INDICES));
}
/// A draw naming a vertex or an index that is not there answers no.
#[test]
fn a_draw_naming_absent_vertices_is_not_an_occluder() {
let mut batch = Batch::new();
batch
.push(
&TRI,
&[0, 1, 2],
Material::solid([1.0; 4]),
BlendMode::SrcOver,
)
.unwrap();
let draw = batch.draws().first().expect("one draw").clone();
assert!(!draw.occludes(&[], &WHITE_TRI_INDICES), "no vertices");
assert!(!draw.occludes(&white_tri(), &[]), "no indices");
assert!(
!draw.occludes(&white_tri(), &[0, 1]),
"fewer indices than the draw names"
);
}
const TARGET: Extent2D = Extent2D::new(100, 80);
/// A quad over the given clip-space box, as `fan_fill` emits one.
fn quad(min: [f32; 2], max: [f32; 2]) -> ([[f32; 2]; 4], [u32; 6]) {
(
[
[min[0], min[1]],
[max[0], min[1]],
[max[0], max[1]],
[min[0], max[1]],
],
[0, 1, 2, 0, 2, 3],
)
}
fn solid_quad(min: [f32; 2], max: [f32; 2]) -> Batch {
let (vertices, indices) = quad(min, max);
let mut batch = Batch::new();
batch
.push(
&vertices,
&indices,
Material::solid([1.0; 4]),
BlendMode::Src,
)
.expect("a quad");
batch
}
/// The whole target, since clip space runs from -1 to 1 on both axes.
#[test]
fn a_full_target_quad_covers_the_whole_target() {
let batch = solid_quad([-1.0, -1.0], [1.0, 1.0]);
let draw = batch.draws().first().expect("one draw");
assert_eq!(
draw.covered(batch.vertices(), batch.indices(), TARGET),
Some(Scissor::covering(TARGET))
);
}
/// Off-center in both axes, which is what pins the orientation.
///
/// A y convention the wrong way round is invisible in a target symmetric about its
/// center line, and it was wrong here first. Clip space runs bottom to top against
/// the target, so a clip y of -1 is the *last* row and this quad is the target's
/// bottom-left quarter. `viewport_projection` in `emblema-geometry` is the authority;
/// what caught the mistake was a scene rather than this test, which is why there is
/// also an end-to-end one over a known rectangle in `emblema`'s `public_api`.
#[test]
fn a_quarter_quad_covers_the_quarter_it_sits_on() {
let batch = solid_quad([-1.0, -1.0], [0.0, -0.5]);
let draw = batch.draws().first().expect("one draw");
assert_eq!(
draw.covered(batch.vertices(), batch.indices(), TARGET),
Some(Scissor::new(0, 60, 50, 20)),
"the bottom-left quarter, not the top-left"
);
}
/// Everything `covered` refuses, each for its own reason.
#[test]
fn nothing_but_a_quad_on_its_own_box_reports_coverage() {
// A triangle: three indices, not six.
let batch = {
let mut b = Batch::new();
b.push(&TRI, &[0, 1, 2], Material::solid([1.0; 4]), BlendMode::Src)
.unwrap();
b
};
let draw = batch.draws()[0].clone();
assert_eq!(
draw.covered(batch.vertices(), batch.indices(), TARGET),
None
);
// Two triangles sharing a *side* rather than the diagonal. Six indices over
// four vertices, and it covers half the box.
let (vertices, _) = quad([-1.0, -1.0], [1.0, 1.0]);
let mut batch = Batch::new();
batch
.push(
&vertices,
&[0, 1, 2, 0, 1, 3],
Material::solid([1.0; 4]),
BlendMode::Src,
)
.unwrap();
let draw = batch.draws()[0].clone();
assert_eq!(
draw.covered(batch.vertices(), batch.indices(), TARGET),
None
);
// A corner pulled inside the box, which is any rotated or sheared rectangle.
let mut batch = Batch::new();
batch
.push(
&[[-1.0, -1.0], [1.0, -1.0], [0.5, 1.0], [-1.0, 1.0]],
&[0, 1, 2, 0, 2, 3],
Material::solid([1.0; 4]),
BlendMode::Src,
)
.unwrap();
let draw = batch.draws()[0].clone();
assert_eq!(
draw.covered(batch.vertices(), batch.indices(), TARGET),
None
);
// A degenerate triangle, which has no area to contribute.
let mut batch = Batch::new();
batch
.push(
&vertices,
&[0, 1, 1, 0, 2, 3],
Material::solid([1.0; 4]),
BlendMode::Src,
)
.unwrap();
let draw = batch.draws()[0].clone();
assert_eq!(
draw.covered(batch.vertices(), batch.indices(), TARGET),
None
);
}
/// A quad narrower than a pixel covers nothing rather than rounding up to one.
#[test]
fn a_subpixel_quad_covers_nothing() {
// Two hundredths of clip space is one pixel across a hundred, and this is a
// fifth of that.
let batch = solid_quad([0.0, 0.0], [0.004, 0.004]);
let draw = batch.draws().first().expect("one draw");
assert_eq!(
draw.covered(batch.vertices(), batch.indices(), TARGET),
Some(Scissor::EMPTY)
);
}
/// A wash under a bar, which is the stacked frame in miniature.
#[test]
fn a_wash_is_narrowed_to_what_the_bar_leaves() {
let (full, indices) = quad([-1.0, -1.0], [1.0, 1.0]);
// The target's top quarter, opaque and solid, so it occludes. Clip y near +1
// is the first row -- see `a_quarter_quad_covers_the_quarter_it_sits_on`.
let (bar, _) = quad([-1.0, 0.5], [1.0, 1.0]);
let mut batch = Batch::new();
batch
.push(
&full,
&indices,
Material::solid([0.1, 0.2, 0.3, 1.0]),
BlendMode::SrcOver,
)
.expect("the wash");
batch
.push(&bar, &indices, Material::solid([1.0; 4]), BlendMode::Src)
.expect("the bar");
assert_eq!(batch.cull_occluded(TARGET), 1);
let draws = batch.draws();
assert_eq!(draws.len(), 2, "one piece plus the bar");
assert_eq!(
draws[0].clip,
Some(Scissor::new(0, 20, 100, 60)),
"the wash keeps only what the bar leaves"
);
assert_eq!(draws[1].clip, None, "the bar is untouched");
}
/// A draw entirely hidden is dropped rather than clipped to nothing.
#[test]
fn a_fully_covered_draw_is_dropped() {
let (full, indices) = quad([-1.0, -1.0], [1.0, 1.0]);
let mut batch = Batch::new();
batch
.push(
&full,
&indices,
Material::solid([0.1, 0.2, 0.3, 1.0]),
BlendMode::SrcOver,
)
.expect("the wash");
batch
.push(&full, &indices, Material::solid([1.0; 4]), BlendMode::Src)
.expect("the cover");
assert_eq!(batch.cull_occluded(TARGET), 1);
assert_eq!(batch.draws().len(), 1, "only the cover is left");
}
/// Order is what decides, and the earlier draw is the one that loses pixels.
///
/// The same two draws the other way round must leave both alone: a wash drawn
/// *over* a bar hides the bar, and the bar is not a safe occluder for it.
#[test]
fn a_draw_in_front_of_an_opaque_one_is_left_alone() {
let (full, indices) = quad([-1.0, -1.0], [1.0, 1.0]);
let (bar, _) = quad([-1.0, -1.0], [1.0, -0.5]);
let mut batch = Batch::new();
batch
.push(&bar, &indices, Material::solid([1.0; 4]), BlendMode::Src)
.expect("the bar");
batch
.push(
&full,
&indices,
Material::solid([0.1, 0.2, 0.3, 1.0]),
BlendMode::SrcOver,
)
.expect("the wash");
// The wash is opaque and covers the bar outright, so the bar goes.
assert_eq!(batch.cull_occluded(TARGET), 1);
assert_eq!(batch.draws().len(), 1);
assert_eq!(batch.draws()[0].clip, None, "the wash is untouched");
}
/// An occluder that cannot prove itself culls nothing.
#[test]
fn a_translucent_cover_narrows_nothing() {
let (full, indices) = quad([-1.0, -1.0], [1.0, 1.0]);
let (bar, _) = quad([-1.0, -1.0], [1.0, -0.5]);
let mut batch = Batch::new();
batch
.push(
&full,
&indices,
Material::solid([1.0; 4]),
BlendMode::SrcOver,
)
.expect("the wash");
batch
.push(
&bar,
&indices,
Material::solid([1.0, 1.0, 1.0, 0.5]),
BlendMode::SrcOver,
)
.expect("a half-transparent bar");
assert_eq!(batch.cull_occluded(TARGET), 0);
assert_eq!(batch.draws().len(), 2);
assert!(batch.draws().iter().all(|d| d.clip.is_none()));
}
/// A draw that writes the stencil keeps every pixel it was given.
///
/// Its scissor decides which pixels get a stencil value, not just which get a
/// color, so narrowing it would change what a later clipped draw is clipped to.
#[test]
fn a_stencil_writing_draw_is_never_narrowed() {
let (full, indices) = quad([-1.0, -1.0], [1.0, 1.0]);
let mut batch = Batch::new();
batch
.push_with(
&full,
&indices,
Material::solid([1.0; 4]),
ColorFilter::None,
BlendMode::Src,
None,
ClipState::narrow(1),
)
.expect("a clip being built");
batch
.push(&full, &indices, Material::solid([1.0; 4]), BlendMode::Src)
.expect("an opaque cover");
assert_eq!(batch.cull_occluded(TARGET), 0);
assert_eq!(batch.draws().len(), 2);
assert_eq!(batch.draws()[0].clip, None);
}
/// An opaque solid fill is what the predicate exists to admit.
#[test]
fn an_opaque_solid_fill_occludes() {
assert!(one(Material::solid([1.0; 4]), BlendMode::SrcOver)
.occludes(&white_tri(), &WHITE_TRI_INDICES));
assert!(one(Material::solid([0.2, 0.3, 0.4, 1.0]), BlendMode::Src)
.occludes(&white_tri(), &WHITE_TRI_INDICES));
}
/// And every reason to refuse is refused, each on its own.
///
/// Written out one condition at a time rather than as a table, because the
/// point of each row is *why* it is unsafe and a table would carry the
/// values without the reason. A wrong yes here is a wrong picture.
#[test]
fn nothing_the_predicate_cannot_prove_occludes() {
// Translucent: the destination shows through, which is the whole
// question.
assert!(
!one(Material::solid([1.0, 1.0, 1.0, 0.5]), BlendMode::SrcOver)
.occludes(&white_tri(), &WHITE_TRI_INDICES)
);
assert!(!one(Material::solid([0.0; 4]), BlendMode::SrcOver)
.occludes(&white_tri(), &WHITE_TRI_INDICES));
// A mode that reads the destination cannot have the destination moved
// out from under it.
for blend in [
BlendMode::Multiply,
BlendMode::Screen,
BlendMode::DstOver,
BlendMode::Xor,
BlendMode::Plus,
] {
assert!(
!one(Material::solid([1.0; 4]), blend).occludes(&white_tri(), &WHITE_TRI_INDICES),
"{blend:?} reads what it is drawn over"
);
}
// The analytic materials blend their own coverage, so an opaque color
// still leaves a soft edge. This is the case the predicate is really
// for: every one of these would pass a naive "is the color opaque" test.
let analytic = [
Material::RoundedRect {
color: [1.0; 4],
half_size: [4.0, 4.0],
to_local: ToLocal::default(),
radius: 1.0,
outer_radius: 1.0,
stroke: 0.0,
},
Material::Ellipse {
color: [1.0; 4],
half_size: [4.0, 4.0],
to_local: ToLocal::default(),
stroke: 0.0,
},
];
for material in analytic {
assert!(
!one(material, BlendMode::SrcOver).occludes(&white_tri(), &WHITE_TRI_INDICES),
"an analytic shape computes coverage and blends it"
);
}
}
/// A filter or a tint can take alpha down after the material produced it.
#[test]
fn a_filter_or_a_tint_refuses_it() {
let mut filtered = one(Material::solid([1.0; 4]), BlendMode::SrcOver);
assert!(
filtered.occludes(&white_tri(), &WHITE_TRI_INDICES),
"the draw is otherwise admissible"
);
filtered.filter = ColorFilter::Blend {
color: [1.0, 1.0, 1.0, 0.25],
mode: BlendMode::SrcOver,
};
assert!(
!filtered.occludes(&white_tri(), &WHITE_TRI_INDICES),
"a blend filter can lower alpha"
);
let mut tinted = one(Material::solid([1.0; 4]), BlendMode::SrcOver);
tinted.tint_blend = BlendMode::Plus;
assert!(
!tinted.occludes(&white_tri(), &WHITE_TRI_INDICES),
"only Modulate is the identity against a solid fill's white"
);
let mut sampled = one(Material::solid([1.0; 4]), BlendMode::SrcOver);
sampled.paint_at_texture_coords = true;
assert!(
!sampled.occludes(&white_tri(), &WHITE_TRI_INDICES),
"reading the paint elsewhere is a value this cannot see"
);
}
/// A stencil-writing draw is sequencing, and a clipped one depends on it.
#[test]
fn anything_touching_the_stencil_refuses_it() {
for stencil in [
ClipState::narrow(0),
ClipState::widen(1),
ClipState::content(1),
] {
let mut draw = one(Material::solid([1.0; 4]), BlendMode::SrcOver);
draw.stencil = stencil;
assert!(
!draw.occludes(&white_tri(), &WHITE_TRI_INDICES),
"{stencil:?} either writes the stencil or depends on it"
);
}
}
}