crcbl-frame 0.2.1

Crucible frame core: render graph, transient pool, texture uploads and the UI pass
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
//! UI compositing pass: renders a [`DrawList`] on top of the target.
//!
//! ```text
//! UiRenderer ──begin_frame──▶ uploads vertex/index buffers from DrawList,
//!      │                     rasterising the glyphs its runs miss, and stages
//!      │                     what changed in the image atlas and glyph pages
//!      │
//!      └──add_passes──▶ [ui-images] ─▶ [ui-glyphs] ─▶ ui-composite ─▶ ui-overlay
//!                       a copy when either atlas changed, then two
//!                       alpha-blended passes onto the same target, after the
//!                       tonemap — and after every pass that writes a texture
//!                       the draw list samples
//! ```
//!
//! The UI pass uses the same target as the tonemap pass, compositing on top
//! with alpha blending. The bitmap font's atlas is a static R8_UNORM texture
//! uploaded once at creation.
//!
//! # Glyph pages upload what changed, the same way
//!
//! [`DrawList::glyphs`] runs draw from the renderer's own [`GlyphAtlas`], which
//! [`begin_frame`](UiRenderer::begin_frame) starts a frame of and rasterises into
//! while it tessellates. Its pages are the layers of one `R8Unorm` `D2Array`
//! image bound at [`GLYPH_PAGES_BINDING`] — every page the atlas may open,
//! allocated at start-up, because a WebGPU texture cannot grow in place and one
//! image is one binding on every backend. What a frame rasterised is staged per
//! page as a dirty rectangle and copied by a `ui-glyphs` copy pass, exactly as
//! the image atlas's `ui-images` is.
//!
//! # The image atlas uploads what changed, inside the frame
//!
//! Beside the glyph atlas the pass binds a second page: the
//! [`ImageAtlas`] this renderer owns, `Rgba8UnormSrgb` and sampled through a
//! linear sampler, which is what [`DrawList::image`] and
//! [`DrawList::nine_slice`] draw from. The page is built with the renderer,
//! like the glyphs, through [`upload_cleared_texture`]: zeroed on the GPU, with
//! only the rectangle of the pictures registered before it
//! ([`with_images`](UiRenderer::with_images)) staged from the host. An image
//! registered after that — through
//! [`images_mut`](UiRenderer::images_mut) — marks a rectangle of the page
//! dirty, and the next [`begin_frame`](UiRenderer::begin_frame) stages just that
//! rectangle into a host-visible buffer. [`add_passes`](UiRenderer::add_passes)
//! then records the copy as a `ui-images` copy pass ahead of the draws, with the
//! page imported so the graph emits the transitions around it: a copy recorded
//! mid-frame outside [`RenderGraph`] would be a barrier outside the graph, which
//! is the one rule `crate`'s docs forbid. A frame with nothing dirty stages
//! nothing, imports nothing and adds no pass.
//!
//! # Colour glyphs are pictures in the image atlas
//!
//! A glyph run's colour glyphs — emoji from a CBDT, sbix or COLR font — are
//! drawn as image quads, not coverage: the tessellation
//! ([`DrawList::to_triangles_with_colors`]) rasterises each into the image
//! atlas through a [`ColorGlyphCache`] this renderer owns, and the images it
//! registered are staged after it, in the same frame. So every list drawn here
//! shows colour emoji with no call of its caller's;
//! [`DrawList::resolve_color_glyphs`] is for a renderer of its own. The glyphs
//! are the atlas's evictable images ([`ImageAtlas::register_evictable`]): a
//! picture registered through [`images_mut`](UiRenderer::images_mut) that
//! finds the page full of emoji takes the room of those the last frame did
//! not draw, so emoji never crowd out an application's icons, and the
//! application's pictures are never evicted.
//!
//! # The menu is in the draw list
//!
//! A [`DrawList`] carries the game's HUD **and** the engine's overlays — the
//! menu, the debug panel, the console — and [`DrawList::begin_overlay`] marks
//! where one ends and the other begins. `crcbl_render`'s `UiRenderer`
//! registers the menu's art in this renderer's image atlas at start-up, through
//! [`with_images`](UiRenderer::with_images), and
//! [`Menu::render`](crcbl_ui::menu::Menu::render) pushes the scrim, the
//! frame and the buttons ahead of the labels, so the scrim dims the HUD and the
//! labels stay legible over the panel because that is the order they went in.
//!
//! It used to be a sprite pass of its own, sandwiched between the draw list's
//! two halves by this module, because this pass had no textured quad. The two
//! halves are still two passes, `ui-composite` and `ui-overlay`, drawn back to
//! back; nothing is between them any more.
//!
//! # A texture the renderer drew, sampled by a UI rectangle
//!
//! [`DrawList::texture`] names a picture by a caller-chosen
//! [`TextureId`](crcbl_ui::TextureId) rather than by atlas texels, and
//! [`add_passes_with_textures`](UiRenderer::add_passes_with_textures) is where
//! the name meets an image: a [`UiTexture`] pairs it with an [`ImageId`] of the
//! same graph — a view's target, typically, which is how an editor viewport or
//! a picture-in-picture is drawn inside the UI rather than under it.
//!
//! **The graph puts the barrier; the caller puts the order.** Each half that
//! samples a texture declares a
//! [`read_image`](crate::graph::PassBuilder::read_image) of it, so the graph
//! emits the transition from whatever state the pass that drew it left it in
//! — its attachment state — to `ShaderRead` between the two. The graph runs
//! passes in the order they were declared and never reorders them, so the
//! caller adds the passes that draw the image before these, as it adds the
//! scene before the UI.
//!
//! **Bound per draw, at set 1.** WebGPU has no array of textures to index, so
//! the portable shape is the sprite pass's per-sheet one: `ui.slang` samples a
//! lone `boundTexture` at set 1, the draw list's expansion reports the index
//! runs that use one ([`TextureRun`]), and a half is drawn as one draw per run
//! plus one per stretch between runs, with a transparent 1×1 bound at set 1
//! for the stretches. A list with no texture in it is still one draw a half. A
//! texture the list names and the call was not handed binds the transparent
//! 1×1 too, so it draws nothing rather than whatever was bound last. Each
//! image's group is built once and kept while frames keep sampling it — see
//! `textures::TextureGroups`.
//!
//! # Per-pass constants are a uniform buffer, on every tier
//!
//! `ui.slang` needs one thing from the CPU each pass — the framebuffer size it
//! divides by to reach NDC — and it takes it from a uniform buffer bound at
//! [`CONSTANTS_BINDING`] of the frame's existing bind group. One per frame in
//! flight, written on the CPU while the pass body records; the pass records no
//! `push_constants` at all.
//!
//! **That is a deliberate refusal of a tier split.** A push constant would
//! deliver the same eight bytes with one indirection fewer, and **WebGPU has no
//! push constants at all** — so it would have made this pass the smallest
//! possible instance of stage 3's old Tier A / Tier B
//! axis, chosen from
//! [`Features::PUSH_CONSTANTS`](crcbl_hal::Features::PUSH_CONSTANTS). It did,
//! until 2026-08: there was a `ConstantDelivery` enum here, two branches through
//! every layout and buffer this file creates, and — because one Slang entry
//! point reads either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
//! one, never both — a whole second shader source, `ui_tier_b.slang`, kept in
//! step with `ui.slang` by a comment. `sprite.slang` had already declined the same trade for the same
//! reason; `crates/crcbl-shaders/shaders/ui.slang`'s header carries the
//! argument. What is left is one source, one artifact per target, and one path
//! through this file.
//!
//! **Not** a dynamic offset, even though the seam has `dynamic_offsets` on
//! [`bind_group`](crcbl_hal::CommandEncoder::bind_group) and
//! [`BindingKind::UniformBuffer`] documents it as *the* portable substitute for
//! a push constant. A dynamic offset buys one buffer sliced per draw; this pass
//! has exactly one draw per frame and already owns one bind group per frame in
//! flight, so the offset would always be zero and the only thing it would add is
//! a way to get it wrong. P7's per-bucket constants are where that vocabulary
//! earns its keep, and the layout here does not foreclose it — `dynamic: false`
//! becomes `dynamic: true` and the offset joins the `bind_group` call.
//!
//! `wgsl/ui.wgsl` declares `@binding(3) @group(0) var<uniform> constants_0`,
//! which is what makes it WGSL a browser will accept: the push-constant form
//! lowered to a module-scope `var<uniform>` with no `@group`/`@binding` at all,
//! which `naga` rejects outright, so the only backend that ingests WGSL —
//! `crcbl-webgpu`, on a WebGPU with no
//! [`PUSH_CONSTANTS`](crcbl_hal::Features::PUSH_CONSTANTS) at all — could not
//! create the module.

use crcbl_hal::{
    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BlendState, BufferDesc,
    BufferHandle, BufferImageCopy, BufferUsage, ColorTargetState, ColorWrites, Device, Extent3d,
    FilterMode, Format, GraphicsPipelineDesc, GraphicsPipelineHandle, HalError, ImageAspect,
    ImageSubresourceLayers, ImageViewHandle, ImageViewType, IndexFormat, LoadOp, MemoryLocation,
    Offset3d, PipelineLayoutDesc, PipelineLayoutHandle, PrimitiveState, QueueHandle, ResourceState,
    SampleType, SamplerAddressMode, SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc,
    ShaderStages, StoreOp, check_portable_storage_buffers,
};

use crcbl_shaders::{Stage, UI};
use crcbl_ui::draw_list::{ColorGlyphs, DrawList, Vertex2d};
use crcbl_ui::font::atlas::{GLYPH_MAX_PAGES, GLYPH_PAGE_SIZE, GLYPH_RASTER_BUDGET, GlyphAtlas};
use crcbl_ui::font::color::ColorGlyphCache;
use crcbl_ui::image::{ImageAtlas, PAGE_SIZE, TexelRect};
use crcbl_ui::text::FontAtlas;

use core::ops::Range;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::counters::FrameCounters;
use crate::graph::{ImageId, ImportedImage, InitialClaim, RenderGraph};
use crate::texture::{
    ClearedTextureDesc, TexturePatch, UploadedTexture, stage_region, upload_cleared_texture,
    upload_texture,
};

mod textures;

use crcbl_ui::draw_list::TextureRun;
pub use textures::UiTexture;
use textures::{TextureGroups, draws, image_of};

/// The constant block matching `ui.slang`'s `UiConstants`.
///
/// `viewport` is the framebuffer size in pixels (width, height). The shader
/// divides position by viewport and maps to NDC.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
struct UiConstants {
    viewport: [f32; 2],
}

/// The binding number the constants buffer occupies, after the atlas (0), its
/// sampler (1) and the vertex storage buffer (2).
pub const CONSTANTS_BINDING: u32 = 3;

/// The binding number the image atlas occupies, after the constants.
pub const IMAGE_ATLAS_BINDING: u32 = 4;

/// The binding number the image atlas's linear sampler occupies.
pub const IMAGE_SAMPLER_BINDING: u32 = 5;

/// The binding number the glyph pages occupy — the last one. They are sampled
/// through the bitmap font's nearest sampler at binding 1.
pub const GLYPH_PAGES_BINDING: u32 = 6;

/// The set a [`DrawList::texture`] rectangle's texture is bound at, alone at
/// its binding 0 and sampled through the image atlas's linear sampler.
pub const TEXTURE_SET: u32 = 1;

/// The image atlas page's format: sRGB-encoded, straight alpha, the sprite
/// pass's sheet format.
const IMAGE_FORMAT: Format = Format::Rgba8UnormSrgb;

/// Bytes reserved for one frame's constants buffer.
///
/// Sixteen rather than the eight [`UiConstants`] occupies: WGSL rounds a
/// `uniform` struct's size up to a multiple of 16, so a binding sized to the
/// Rust struct is one naga validation error rather than a saving. The trailing
/// bytes are never written and never read.
const CONSTANTS_UNIFORM_SIZE: u64 = 16;

/// How many frames of vertex/index buffers to keep in flight.
const FRAMES_IN_FLIGHT: usize = 2;

/// Starting size of each ring buffer, in bytes.
const INITIAL_RING_BYTES: u64 = 1024;

/// The size a ring buffer grows to when `needed` bytes no longer fit.
///
/// Doubling rather than fitting exactly, so a UI that grows a few vertices per
/// frame reallocates a handful of times rather than every frame.
fn grown(needed: u64) -> u64 {
    needed
        .max(INITIAL_RING_BYTES)
        .next_power_of_two()
        .next_multiple_of(256)
}

/// The UI compositing renderer.
///
/// Created once; `begin_frame` uploads the current frame's geometry, and
/// `add_passes` inserts the draw passes into the graph.
#[derive(Debug)]
pub struct UiRenderer {
    // Pipeline state
    pipeline_layout: PipelineLayoutHandle,
    pipeline: GraphicsPipelineHandle,
    bind_group_layout: BindGroupLayoutHandle,

    // Glyph atlas
    atlas: UploadedTexture,
    atlas_sampler: SamplerHandle,

    /// The pictures [`DrawList::image`] draws, and the page they are on.
    images: ImageAtlas,
    image_page: UploadedTexture,
    image_sampler: SamplerHandle,
    /// The staged copy of a dirty rectangle, per frame in flight: a slot's
    /// buffer is released when its turn of the ring comes round again, which is
    /// when the frame that copied from it has finished.
    image_staging: Vec<Option<BufferHandle>>,
    /// This frame's copy, when [`begin_frame`](Self::begin_frame) staged one.
    image_upload: Option<ImageUpload>,
    /// Set by the copy pass's body once the copy is recorded. A frame that
    /// staged an upload and never recorded it puts the rectangle back on the
    /// atlas for the next frame to try again.
    image_recorded: Arc<AtomicBool>,

    /// The glyphs [`DrawList::glyphs`] runs draw, rasterised on demand.
    glyphs: GlyphAtlas,
    /// Its pages, one layer each.
    glyph_pages: UploadedTexture,
    /// The staged copies of dirty page rectangles, per frame in flight, freed
    /// on the slot's next turn as [`Self::image_staging`] is.
    glyph_staging: Vec<Vec<BufferHandle>>,
    /// This frame's page copies.
    glyph_uploads: Vec<GlyphUpload>,
    /// [`Self::image_recorded`]'s counterpart for the page copies.
    glyph_recorded: Arc<AtomicBool>,
    /// The colour glyphs — emoji — a run draws, rasterised into
    /// [`Self::images`] while the list is tessellated; see the module docs.
    colors: ColorGlyphCache,

    /// Set 1's layout: one sampled texture — see the module docs.
    texture_layout: BindGroupLayoutHandle,
    /// A transparent 1×1, and the set-1 group naming it: what every draw that
    /// samples no renderer-owned texture binds.
    blank: UploadedTexture,
    blank_group: BindGroupHandle,
    /// The set-1 groups naming the textures frames sampled.
    texture_groups: TextureGroups,
    /// Per frame in flight, the index runs that sample a renderer-owned
    /// texture, as [`begin_frame`](Self::begin_frame) tessellated them.
    last_texture_runs: Vec<Vec<TextureRun>>,

    // Per-frame bind groups (each contains atlas+sampler+vertex_buffer+constants)
    frame_groups: Vec<BindGroupHandle>,
    vertex_buffers: Vec<BufferHandle>,
    index_buffers: Vec<BufferHandle>,
    frame: usize,

    /// One constants buffer per frame in flight, rotating with the geometry
    /// rings so a frame still in flight cannot have its viewport overwritten.
    constant_buffers: Vec<BufferHandle>,

    /// How many **bytes** each ring buffer holds. Compared against the bytes a
    /// frame needs; the counts below are *elements* and comparing the two is
    /// what used to make a steady-state frame destroy and recreate both
    /// buffers and the bind group every time.
    vertex_capacity: Vec<u64>,
    index_capacity: Vec<u64>,

    // Element counts, for the draw call and for "is there anything to draw".
    last_vertex_count: Vec<usize>,
    last_index_count: Vec<usize>,

    /// Where the overlay's indices start in [`Self::last_index_count`]'s range,
    /// per frame in flight — [`crcbl_ui::draw_list::Triangles::overlay`] as the
    /// upload left it. The one number that turns a frame's geometry into the
    /// two ranges [`UiRenderer::add_passes`] draws.
    last_overlay_index: Vec<usize>,

    /// The format the pipeline was built for. Dynamic rendering checks the
    /// pipeline's colour-target format against the attachment at pass-begin, so
    /// a swapchain in a different format needs a different pipeline.
    target_format: Format,

    destroyed: bool,
}

impl UiRenderer {
    /// Creates the UI pipeline, glyph atlas, and per-frame geometry buffers.
    ///
    /// `target_format` must be the format of the image the pass composites
    /// onto — normally the swapchain's, which is `Bgra8UnormSrgb` on most
    /// desktop platforms. Under dynamic rendering the pipeline's colour-target
    /// format is checked against the attachment at pass-begin time rather than
    /// at creation, so a pipeline built for the wrong one fails the frame, not
    /// the constructor. `crcbl_render`'s `ForwardRenderer::new` takes it for
    /// the same reason.
    ///
    /// The atlas is uploaded immediately via a staging copy. The image atlas
    /// starts empty; [`with_images`](Self::with_images) starts it with pictures
    /// already registered.
    ///
    /// This pass asks for no device feature of its own — its constants are a
    /// uniform buffer, which every target has — so a browser and a native
    /// Vulkan device build the same pipeline from the same artifact.
    ///
    /// # Errors
    ///
    /// [`HalError`] from any seam call. A failure part-way through releases
    /// everything already created, so a caller that retries or exits leaves
    /// nothing behind.
    pub fn new(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
    ) -> Result<Self, HalError> {
        Self::with_images(device, queue, target_format, ImageAtlas::new())
    }

    /// [`new`](Self::new), with `images` as the image atlas: the pictures
    /// registered in it are uploaded with the page, at start-up, rather than
    /// copied in a frame.
    ///
    /// For art that is always on screen from the first frame — the engine's
    /// menu skin is registered this way by `crcbl_render`'s `UiRenderer`. A
    /// picture registered later through [`images_mut`](Self::images_mut) works
    /// too, one frame's copy later.
    ///
    /// # Errors
    ///
    /// As [`new`](Self::new).
    pub fn with_images(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
        images: ImageAtlas,
    ) -> Result<Self, HalError> {
        let mut rollback = Rollback::default();
        match Self::build(device, queue, target_format, images, &mut rollback) {
            Ok(renderer) => Ok(renderer),
            Err(error) => {
                rollback.run(device);
                Err(error)
            }
        }
    }

    /// The body of [`UiRenderer::with_images`], recording what it has created
    /// into `rollback` as it goes.
    fn build(
        device: &dyn Device,
        queue: QueueHandle,
        target_format: Format,
        mut images: ImageAtlas,
        rollback: &mut Rollback,
    ) -> Result<Self, HalError> {
        let atlas = FontAtlas::built_in();
        let (atlas_w, atlas_h, atlas_pixels) = atlas.glyph_bitmap();

        // Upload glyph atlas texture via staging.
        let atlas = upload_texture(
            device,
            queue,
            "ui glyph atlas",
            Format::R8Unorm,
            atlas_w,
            atlas_h,
            &atlas_pixels,
        )?;
        rollback.textures.push(atlas);

        let atlas_sampler = device.create_sampler(&SamplerDesc {
            label: Some("ui glyph atlas"),
            mag_filter: FilterMode::Nearest,
            min_filter: FilterMode::Nearest,
            mip_filter: FilterMode::Nearest,
            address_mode: [SamplerAddressMode::ClampToEdge; 3],
            ..SamplerDesc::default()
        })?;
        rollback.samplers.push(atlas_sampler);

        // The image atlas's page, created once, at start-up — zeroed on the GPU
        // with only the caller's registered rectangle staged from the host, and
        // legal here for the same reason as the glyphs. What changes later is
        // copied inside a frame; see the module docs.
        // Taken rather than read: the rectangle is on the GPU once the page is,
        // so nothing is owed.
        let registered = images.take_dirty().map(|rect| (rect, images.region(rect)));
        let patches: Vec<TexturePatch<'_>> = registered
            .iter()
            .map(|(rect, pixels)| TexturePatch {
                layer: 0,
                x: rect.x,
                y: rect.y,
                width: rect.width,
                height: rect.height,
                pixels,
            })
            .collect();
        let image_page = upload_cleared_texture(
            device,
            queue,
            &ClearedTextureDesc {
                label: "ui image atlas",
                format: IMAGE_FORMAT,
                width: PAGE_SIZE,
                height: PAGE_SIZE,
                layers: 1,
                view_type: ImageViewType::D2,
                patches: &patches,
            },
        )?;
        rollback.textures.push(image_page);
        // Linear, for the shader's sharp-bilinear bend — see `ui.slang`.
        let image_sampler = device.create_sampler(&SamplerDesc {
            label: Some("ui image atlas"),
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            mip_filter: FilterMode::Nearest,
            address_mode: [SamplerAddressMode::ClampToEdge; 3],
            ..SamplerDesc::default()
        })?;
        rollback.samplers.push(image_sampler);

        // The glyph pages: every page the atlas may open, empty, once — zeroed on
        // the GPU rather than sent from the host. What the atlas rasterises later
        // is copied inside a frame; see the module docs.
        let glyphs = GlyphAtlas::new(GLYPH_PAGE_SIZE, GLYPH_MAX_PAGES, GLYPH_RASTER_BUDGET);
        let glyph_pages = upload_cleared_texture(
            device,
            queue,
            &ClearedTextureDesc {
                label: "ui glyph pages",
                format: Format::R8Unorm,
                width: GLYPH_PAGE_SIZE,
                height: GLYPH_PAGE_SIZE,
                layers: GLYPH_MAX_PAGES as u32,
                view_type: ImageViewType::D2Array,
                patches: &[],
            },
        )?;
        rollback.textures.push(glyph_pages);

        // Bind group layout: atlas texture, sampler, vertex storage buffer, the
        // constants uniform buffer, the image atlas and its sampler, then the
        // glyph pages.
        let layout_entries = [
            BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 1,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::Sampler { comparison: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: 2,
                visibility: ShaderStages::VERTEX,
                kind: BindingKind::StorageBuffer {
                    read_only: true,
                    dynamic: false,
                    stride: size_of::<Vertex2d>() as u32,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: CONSTANTS_BINDING,
                visibility: ShaderStages::VERTEX,
                // `dynamic: false`: one buffer per frame in flight, bound whole.
                // See this module's docs on why a dynamic offset would only ever
                // be zero here.
                kind: BindingKind::UniformBuffer { dynamic: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: IMAGE_ATLAS_BINDING,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: IMAGE_SAMPLER_BINDING,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::Sampler { comparison: false },
                count: 1,
                flags: BindingFlags::empty(),
            },
            BindGroupLayoutEntry {
                binding: GLYPH_PAGES_BINDING,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2Array,
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            },
        ];
        let layout_desc = BindGroupLayoutDesc {
            label: Some("ui pass"),
            entries: &layout_entries,
        };
        check_portable_storage_buffers(Some("ui"), &[&layout_desc])?;
        let bind_group_layout = device.create_bind_group_layout(&layout_desc)?;
        rollback.bind_group_layouts.push(bind_group_layout);

        // Set 1: the renderer-owned texture a `DrawList::texture` rectangle
        // samples, and the transparent 1×1 every other draw binds there.
        let texture_layout = device.create_bind_group_layout(&BindGroupLayoutDesc {
            label: Some("ui texture"),
            entries: &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::Float,
                },
                count: 1,
                flags: BindingFlags::empty(),
            }],
        })?;
        rollback.bind_group_layouts.push(texture_layout);
        let blank = upload_cleared_texture(
            device,
            queue,
            &ClearedTextureDesc {
                label: "ui blank texture",
                format: Format::Rgba8Unorm,
                width: 1,
                height: 1,
                layers: 1,
                view_type: ImageViewType::D2,
                patches: &[],
            },
        )?;
        rollback.textures.push(blank);
        let blank_group = device.create_bind_group(&BindGroupDesc {
            label: Some("ui blank texture"),
            layout: texture_layout,
            entries: &[BindGroupEntry {
                binding: 0,
                array_index: 0,
                resource: BindingResource::ImageView(blank.view),
            }],
            variable_count: None,
        })?;
        rollback.bind_groups.push(blank_group);

        // Per-frame bind groups (atlas/sampler are static, the rest rotate)
        let mut frame_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut vertex_buffers = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut index_buffers = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut constant_buffers = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut last_vertex_count = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut last_index_count = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut last_overlay_index = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut vertex_capacity = Vec::with_capacity(FRAMES_IN_FLIGHT);
        let mut index_capacity = Vec::with_capacity(FRAMES_IN_FLIGHT);
        for _ in 0..FRAMES_IN_FLIGHT {
            let vb = device.create_buffer(&BufferDesc {
                label: Some("ui vertices"),
                size: INITIAL_RING_BYTES,
                usage: BufferUsage::STORAGE,
                memory: MemoryLocation::HostUpload,
            })?;
            rollback.buffers.push(vb);
            let ib = device.create_buffer(&BufferDesc {
                label: Some("ui indices"),
                size: INITIAL_RING_BYTES,
                usage: BufferUsage::INDEX,
                memory: MemoryLocation::HostUpload,
            })?;
            rollback.buffers.push(ib);
            let cb = device.create_buffer(&BufferDesc {
                label: Some("ui constants"),
                size: CONSTANTS_UNIFORM_SIZE,
                usage: BufferUsage::UNIFORM,
                memory: MemoryLocation::HostUpload,
            })?;
            rollback.buffers.push(cb);
            constant_buffers.push(cb);
            let bg = device.create_bind_group(&BindGroupDesc {
                label: Some("ui frame"),
                layout: bind_group_layout,
                entries: &frame_entries(
                    FrameTextures {
                        glyphs: (atlas.view, atlas_sampler),
                        images: (image_page.view, image_sampler),
                        glyph_pages: glyph_pages.view,
                    },
                    vb,
                    cb,
                ),
                variable_count: None,
            })?;
            rollback.bind_groups.push(bg);
            vertex_buffers.push(vb);
            index_buffers.push(ib);
            frame_groups.push(bg);
            last_vertex_count.push(0);
            last_index_count.push(0);
            last_overlay_index.push(0);
            vertex_capacity.push(INITIAL_RING_BYTES);
            index_capacity.push(INITIAL_RING_BYTES);
        }

        let set_layouts = [bind_group_layout, texture_layout];
        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("ui"),
            bind_group_layouts: &set_layouts,
            // No range at all: the block arrives through the bind group, and a
            // backend without push constants must refuse a range rather than
            // drop the writes silently — which is exactly what the null backend
            // does, and is how the browser used to lose its HUD.
            push_constants: None,
        })?;
        rollback.pipeline_layouts.push(pipeline_layout);

        // Entry points resolved before the module exists: a manifest that
        // disagreed with the artifact would otherwise fail inside the descriptor
        // literal, with the module already created and nothing holding it.
        let vertex_entry = entry(&UI, Stage::Vertex)?;
        let fragment_entry = entry(&UI, Stage::Fragment)?;
        let ui_module = device.create_shader_module(&ShaderModuleDesc {
            label: Some("ui.slang"),
            spirv: UI.spirv(),
            wgsl: UI.wgsl(),
            msl: UI.msl(),
            // One container per entry point, both of them, in one module; see
            // `crcbl_render::forward`.
            dxil: &UI.dxil_containers(),
        })?;
        let ui_targets = [ColorTargetState {
            format: target_format,
            blend: Some(BlendState::alpha()),
            write_mask: ColorWrites::ALL,
        }];
        let ui_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
            label: Some("ui compositing"),
            layout: pipeline_layout,
            vertex: ShaderEntry {
                module: ui_module,
                entry_point: vertex_entry,
            },
            fragment: Some(ShaderEntry {
                module: ui_module,
                entry_point: fragment_entry,
            }),
            primitive: PrimitiveState::default(), // TriangleList, no culling
            depth_stencil: None,
            multisample: Default::default(),
            color_targets: &ui_targets,
        });
        device.destroy_shader_module(ui_module);
        let pipeline = ui_pipeline?;
        rollback.pipelines.push(pipeline);

        Ok(Self {
            pipeline_layout,
            pipeline,
            bind_group_layout,
            atlas,
            atlas_sampler,
            images,
            image_page,
            image_sampler,
            image_staging: vec![None; FRAMES_IN_FLIGHT],
            image_upload: None,
            image_recorded: Arc::new(AtomicBool::new(false)),
            glyphs,
            glyph_pages,
            glyph_staging: vec![Vec::new(); FRAMES_IN_FLIGHT],
            glyph_uploads: Vec::new(),
            glyph_recorded: Arc::new(AtomicBool::new(false)),
            colors: ColorGlyphCache::new(),
            texture_layout,
            blank,
            blank_group,
            texture_groups: TextureGroups::new(FRAMES_IN_FLIGHT),
            last_texture_runs: vec![Vec::new(); FRAMES_IN_FLIGHT],
            frame_groups,
            vertex_buffers,
            index_buffers,
            frame: 0,
            constant_buffers,
            vertex_capacity,
            index_capacity,
            last_vertex_count,
            last_index_count,
            last_overlay_index,
            target_format,
            destroyed: false,
        })
    }

    /// The format the compositing pass renders into.
    #[must_use]
    pub const fn target_format(&self) -> Format {
        self.target_format
    }

    /// The image atlas [`DrawList::image`] and [`DrawList::nine_slice`] draw
    /// from.
    #[must_use]
    pub const fn images(&self) -> &ImageAtlas {
        &self.images
    }

    /// The image atlas, to register pictures into.
    ///
    /// A registration marks the texels it wrote dirty, and the next
    /// [`begin_frame`](Self::begin_frame) uploads that rectangle and nothing
    /// else — see the module docs. The [`AtlasImage`](crcbl_ui::AtlasImage) it
    /// returns is valid in a draw list from that frame on.
    pub const fn images_mut(&mut self) -> &mut ImageAtlas {
        &mut self.images
    }

    /// The glyph atlas [`DrawList::glyphs`] runs are rasterised into: what it
    /// holds, and what it did in the last [`begin_frame`](Self::begin_frame).
    #[must_use]
    pub const fn glyphs(&self) -> &GlyphAtlas {
        &self.glyphs
    }

    /// Uploads the draw list's triangulated geometry and advances the ring.
    ///
    /// Call once per frame before `add_passes`. If the draw list is empty, the
    /// frame stores zero geometry and the passes draw nothing.
    ///
    /// **One expansion, both halves.** The list is tessellated once and the
    /// index where [`DrawList::begin_overlay`] cut it comes back with the
    /// geometry, so the two passes below share one upload and cannot disagree
    /// about where the HUD ends.
    ///
    /// **One glyph-atlas frame per call.** The tessellation rasterises every
    /// glyph a run misses, up to the atlas's budget, and what it put on a page
    /// is staged after it; a glyph past the budget is left out of this frame
    /// and drawn by a later one.
    ///
    /// **Colour glyphs come with it.** The tessellation draws each colour
    /// glyph — an emoji — as an image quad, registering its picture in the
    /// image atlas through this renderer's colour-glyph cache, and the image
    /// atlas is staged after the tessellation, so the picture uploads in the
    /// frame that draws it. See the module docs.
    ///
    /// # Errors
    ///
    /// [`HalError`] if buffer upload failed.
    pub fn begin_frame(
        &mut self,
        device: &dyn Device,
        draw_list: &DrawList,
        atlas: &FontAtlas,
        scale: f32,
    ) -> Result<(), HalError> {
        self.frame = (self.frame + 1) % FRAMES_IN_FLIGHT;
        let idx = self.frame;
        self.texture_groups.retire(device, idx);

        self.glyphs.begin_frame();
        self.colors.begin_frame(&mut self.images);
        let colors = ColorGlyphs {
            cache: &mut self.colors,
            images: &mut self.images,
        };
        let crcbl_ui::draw_list::Triangles {
            vertices,
            indices,
            overlay,
            textures,
        } = draw_list.to_triangles_with_colors(
            Some(atlas),
            Some(&mut self.glyphs),
            Some(colors),
            scale,
        );
        // After the tessellation, so a colour glyph it registered uploads in
        // the frame that draws it.
        self.stage_images(device, idx)?;
        self.stage_glyphs(device, idx)?;

        // Grow the ring buffers only when this frame genuinely needs more room.
        // Both sides of every comparison here are **bytes**.
        let vb_needed = (vertices.len() * std::mem::size_of::<Vertex2d>()) as u64;
        let ib_needed = (indices.len() * std::mem::size_of::<u32>()) as u64;

        // The vertex buffer is named by the frame's bind group, so replacing it
        // is the only thing that makes the group stale.
        let mut vertex_buffer_replaced = false;
        if vb_needed > self.vertex_capacity[idx] {
            let size = grown(vb_needed);
            // Create before destroying: a creation that fails must not leave a
            // destroyed handle in the struct for `destroy` to hand back to the
            // device a second time. `TransientPool::image` has the same shape.
            let fresh = device.create_buffer(&BufferDesc {
                label: Some("ui vertices"),
                size,
                usage: BufferUsage::STORAGE,
                memory: MemoryLocation::HostUpload,
            })?;
            device.destroy_buffer(std::mem::replace(&mut self.vertex_buffers[idx], fresh));
            self.vertex_capacity[idx] = size;
            vertex_buffer_replaced = true;
        }
        if ib_needed > self.index_capacity[idx] {
            let size = grown(ib_needed);
            let fresh = device.create_buffer(&BufferDesc {
                label: Some("ui indices"),
                size,
                usage: BufferUsage::INDEX,
                memory: MemoryLocation::HostUpload,
            })?;
            device.destroy_buffer(std::mem::replace(&mut self.index_buffers[idx], fresh));
            self.index_capacity[idx] = size;
        }
        // Upload vertex data
        if !vertices.is_empty() {
            let bytes: &[u8] = bytemuck::cast_slice(&vertices);
            device.write_buffer(self.vertex_buffers[idx], 0, bytes)?;
        }

        // Upload index data
        if !indices.is_empty() {
            let bytes: &[u8] = bytemuck::cast_slice(&indices);
            device.write_buffer(self.index_buffers[idx], 0, bytes)?;
        }

        // The counts describe the bytes just written: committing them only after
        // the uploads succeeded keeps a failed write from drawing new counts over
        // stale indices (a Vulkan OOB index read).
        self.last_vertex_count[idx] = vertices.len();
        self.last_index_count[idx] = indices.len();
        self.last_overlay_index[idx] = overlay;
        self.last_texture_runs[idx] = textures;

        // Only a new vertex buffer needs a new bind group; the atlas and the
        // sampler never change, so a steady-state frame writes no descriptors.
        if vertex_buffer_replaced {
            let entries = frame_entries(
                FrameTextures {
                    glyphs: (self.atlas.view, self.atlas_sampler),
                    images: (self.image_page.view, self.image_sampler),
                    glyph_pages: self.glyph_pages.view,
                },
                self.vertex_buffers[idx],
                self.constant_buffers[idx],
            );
            let fresh = device.create_bind_group(&BindGroupDesc {
                label: Some("ui frame"),
                layout: self.bind_group_layout,
                entries: &entries,
                variable_count: None,
            })?;
            device.destroy_bind_group(std::mem::replace(&mut self.frame_groups[idx], fresh));
        }

        Ok(())
    }

    /// Stages whatever of the image atlas changed since the last upload, for
    /// this frame's `ui-images` copy pass.
    ///
    /// Also where last frame's staging is settled: an upload that was staged
    /// and never recorded — a graph built and dropped, or `add_passes` never
    /// called — hands its rectangle back to the atlas so it is not lost, and
    /// this slot's buffer from a whole ring ago is released.
    fn stage_images(&mut self, device: &dyn Device, idx: usize) -> Result<(), HalError> {
        if let Some(upload) = self.image_upload.take()
            && !self.image_recorded.swap(false, Ordering::Relaxed)
        {
            self.images.mark_dirty(upload.rect);
        }
        if let Some(stale) = self.image_staging[idx].take() {
            device.destroy_buffer(stale);
        }
        let Some(rect) = self.images.take_dirty() else {
            return Ok(());
        };
        let staged = stage_region(
            device,
            "ui image atlas staging",
            IMAGE_FORMAT,
            (rect.width, rect.height),
            &self.images.region(rect),
        );
        let (buffer, row_texels) = match staged {
            Ok(staged) => staged,
            Err(error) => {
                // Not lost: the next frame stages it again.
                self.images.mark_dirty(rect);
                return Err(error);
            }
        };
        self.image_staging[idx] = Some(buffer);
        self.image_recorded.store(false, Ordering::Relaxed);
        self.image_upload = Some(ImageUpload {
            staging: buffer,
            rect,
            row_texels,
        });
        Ok(())
    }

    /// Stages every glyph page rectangle this frame's tessellation dirtied, for
    /// the `ui-glyphs` copy pass — and settles last frame's, as
    /// [`stage_images`](Self::stage_images) does for the image atlas.
    fn stage_glyphs(&mut self, device: &dyn Device, idx: usize) -> Result<(), HalError> {
        if !self.glyph_recorded.swap(false, Ordering::Relaxed) {
            for upload in self.glyph_uploads.drain(..) {
                self.glyphs.mark_dirty(upload.page as usize, upload.rect);
            }
        }
        self.glyph_uploads.clear();
        for stale in self.glyph_staging[idx].drain(..) {
            device.destroy_buffer(stale);
        }
        for page in 0..self.glyphs.page_count() {
            let Some(rect) = self.glyphs.take_dirty(page) else {
                continue;
            };
            let staged = stage_region(
                device,
                "ui glyph page staging",
                Format::R8Unorm,
                (rect.width, rect.height),
                &self.glyphs.region(page, rect),
            );
            let (staging, row_texels) = match staged {
                Ok(staged) => staged,
                Err(error) => {
                    // Not lost: this rectangle and every one staged before it
                    // this frame go back on the atlas for the next frame.
                    self.glyphs.mark_dirty(page, rect);
                    for upload in self.glyph_uploads.drain(..) {
                        self.glyphs.mark_dirty(upload.page as usize, upload.rect);
                    }
                    return Err(error);
                }
            };
            self.glyph_staging[idx].push(staging);
            self.glyph_uploads.push(GlyphUpload {
                staging,
                page: page as u32,
                rect,
                row_texels,
            });
        }
        Ok(())
    }

    /// The most passes [`add_passes`](Self::add_passes) adds to a frame.
    ///
    /// Four: the image atlas's `ui-images` copy on a frame that registered a
    /// picture, the glyph pages' `ui-glyphs` copy on a frame that rasterised a
    /// glyph, then the HUD half and the overlay half, either of which a frame
    /// can leave empty — a frame with no menu and no console draws only the
    /// first, and a frame with an empty draw list draws neither.
    ///
    /// The most rather than the count. What a caller sizing
    /// [`PassTimers`](crate::timing::PassTimers) adds up — see that module's
    /// docs.
    pub const MAX_PASSES: u32 = 4;

    /// This frame's two index ranges: the HUD half, then the overlay half.
    ///
    /// **The one place the split is computed**, so
    /// [`counters`](Self::counters) and [`add_passes`](Self::add_passes) cannot
    /// disagree about which halves a frame draws — the pair the counters' docs
    /// promise. Both are empty on a frame with nothing uploaded, and the second
    /// is empty on a frame whose draw list was never cut.
    fn segments(&self) -> (Range<u32>, Range<u32>) {
        let idx = self.frame;
        if self.last_vertex_count[idx] == 0 {
            return (0..0, 0..0);
        }
        let total = self.last_index_count[idx] as u32;
        // Clamped rather than trusted: the two ranges must partition the index
        // buffer, and a cut past its end would otherwise hand the draw call a
        // range the buffer does not hold.
        let split = (self.last_overlay_index[idx] as u32).min(total);
        (0..split, split..total)
    }

    /// What the last [`begin_frame`](Self::begin_frame) left this pass to draw.
    ///
    /// **Off `segments`, the same two index ranges
    /// [`add_passes`](Self::add_passes) branches on**, and off the same split
    /// of each into draws, so a half this reports as drawn is a half that gets
    /// a pass and the two cannot disagree. One draw of one instance per
    /// non-empty half and texture run: a frame with no overlay and no texture
    /// on it reports one, a paused frame reports two, a frame with a view drawn
    /// in the middle of its HUD reports three, and an empty draw list reports
    /// nothing.
    ///
    /// The triangles are the index counts of the halves actually drawn —
    /// `draw_list.to_triangles_split` produced them and the pipeline's
    /// `PrimitiveState::default()` is a triangle list, so the count is a
    /// division and not an estimate.
    #[must_use]
    pub fn counters(&self) -> FrameCounters {
        let (below, above) = self.segments();
        let runs = &self.last_texture_runs[self.frame];
        let recorded = (draws(below.clone(), runs).len() + draws(above.clone(), runs).len()) as u64;
        if recorded == 0 {
            return FrameCounters::default();
        }
        FrameCounters {
            draws: recorded,
            instances: recorded,
            drawn: Some(recorded),
            triangles: Some((below.len() + above.len()) as u64 / 3),
            // No cluster geometry and no readback: a known zero and no second
            // lag to declare — see [`crate::counters`].
            clusters: Some(0),
            cull_frame: None,
        }
    }

    /// Adds the UI's passes to `graph`, drawing on top of `target`.
    ///
    /// In order: `ui-images` when [`begin_frame`](Self::begin_frame) staged a
    /// changed rectangle of the image atlas, `ui-glyphs` when it staged glyph
    /// page rectangles, then `ui-composite` for the commands below
    /// [`DrawList::begin_overlay`]'s cut — the game's HUD and GUI — then
    /// `ui-overlay` for the commands above it — the menu, the debug panel and
    /// the console.
    ///
    /// A half with no triangles in it adds **no pass at all** rather than an
    /// empty one, the rule this pass has always had — so an unpaused frame with
    /// the console closed still records exactly one pass, named as it always
    /// was.
    ///
    /// Each pass reads nothing except its own vertex buffer; both blend onto
    /// the target using alpha blending. Call after the tonemap pass.
    ///
    /// `extent` is the target's size in pixels, which the shader divides by to
    /// reach NDC. It is *not* used to set the viewport or the scissor: the
    /// graph already sets both from the pass's own render area
    /// ([`CompiledGraph::execute`](crate::graph::CompiledGraph::execute)), and a
    /// body that set them again could only disagree with it.
    ///
    /// `extent` is also the *only* source of the viewport constants, which is
    /// why the uniform buffer is written in the pass body rather than in
    /// [`begin_frame`](Self::begin_frame): a second extent taken a second time
    /// is a second thing that can disagree.
    ///
    /// [`add_passes_with_textures`](Self::add_passes_with_textures) with no
    /// texture handed over: a [`DrawList::texture`] rectangle draws nothing.
    pub fn add_passes<'a>(
        &'a self,
        graph: &mut RenderGraph<'a>,
        target: ImageId,
        extent: (u32, u32),
    ) {
        self.add_passes_with_textures(graph, target, extent, &[]);
    }

    /// [`add_passes`](Self::add_passes) for a frame whose draw list samples
    /// renderer-owned textures: each [`UiTexture`] says which image of `graph`
    /// a [`TextureId`](crcbl_ui::TextureId) stands for this frame.
    ///
    /// A half that samples one of them declares that it reads the image, so
    /// the graph puts the barrier between it and the passes that drew it — a
    /// view's frame, say — which the caller adds first; see the module docs.
    /// The first pairing
    /// naming an id wins, and an id the list uses that none names draws
    /// transparent.
    ///
    /// The image must be sampleable as filterable float — a colour target of
    /// the forward renderer's format is — and must not be `target`, which the
    /// same pass is drawing into.
    pub fn add_passes_with_textures<'a>(
        &'a self,
        graph: &mut RenderGraph<'a>,
        target: ImageId,
        extent: (u32, u32),
        textures: &[UiTexture],
    ) {
        let (below, above) = self.segments();
        let pages = [self.add_image_upload(graph), self.add_glyph_upload(graph)];
        let halves = [(below, "ui-composite"), (above, "ui-overlay")];
        for (segment, label) in halves {
            self.add_segment(
                graph,
                Segment {
                    target,
                    extent,
                    label,
                    indices: segment,
                },
                pages,
                textures,
            );
        }
    }

    /// Adds the `ui-glyphs` copy of this frame's staged page rectangles, and
    /// returns the page image as the graph knows it — or does nothing and
    /// returns `None` on a frame that staged nothing.
    ///
    /// Imported tracked in [`ResourceState::ShaderRead`] and back, for
    /// [`add_image_upload`](Self::add_image_upload)'s reason. One copy per
    /// rectangle, each into its page's layer.
    fn add_glyph_upload<'a>(&'a self, graph: &mut RenderGraph<'a>) -> Option<ImageId> {
        if self.glyph_uploads.is_empty() {
            return None;
        }
        let pages = graph.import_image(
            "ui glyph pages",
            ImportedImage {
                image: self.glyph_pages.image,
                view: self.glyph_pages.view,
                format: Format::R8Unorm,
                extent: (GLYPH_PAGE_SIZE, GLYPH_PAGE_SIZE),
                initial: ResourceState::ShaderRead,
                claim: InitialClaim::Tracked,
                final_state: ResourceState::ShaderRead,
            },
        );
        let uploads = self.glyph_uploads.clone();
        let recorded = Arc::clone(&self.glyph_recorded);
        graph
            .add_copy_pass("ui-glyphs")
            .use_image(pages, ResourceState::TransferDst)
            .execute(move |ctx| {
                let image = ctx.image(pages);
                for upload in &uploads {
                    ctx.encoder().copy_buffer_to_image(&BufferImageCopy {
                        buffer: upload.staging,
                        buffer_offset: 0,
                        buffer_row_length: upload.row_texels,
                        buffer_image_height: upload.rect.height,
                        image,
                        image_subresource: ImageSubresourceLayers {
                            aspect: ImageAspect::COLOR,
                            mip: 0,
                            base_layer: upload.page,
                            layer_count: 1,
                        },
                        image_offset: Offset3d {
                            x: upload.rect.x as i32,
                            y: upload.rect.y as i32,
                            z: 0,
                        },
                        image_extent: Extent3d::d2(upload.rect.width, upload.rect.height),
                    });
                }
                recorded.store(true, Ordering::Relaxed);
            });
        Some(pages)
    }

    /// Adds the `ui-images` copy of this frame's staged rectangle, and returns
    /// the page as the graph knows it — or does nothing and returns `None` on a
    /// frame that staged nothing.
    ///
    /// The page is imported **tracked**, in [`ResourceState::ShaderRead`] and
    /// back to it: that is where the start-up upload left it and where every
    /// frame's graph leaves it, so the claim is one the pool's ledger can check.
    fn add_image_upload<'a>(&'a self, graph: &mut RenderGraph<'a>) -> Option<ImageId> {
        let upload = self.image_upload?;
        let page = graph.import_image(
            "ui image atlas",
            ImportedImage {
                image: self.image_page.image,
                view: self.image_page.view,
                format: IMAGE_FORMAT,
                extent: (PAGE_SIZE, PAGE_SIZE),
                initial: ResourceState::ShaderRead,
                claim: InitialClaim::Tracked,
                final_state: ResourceState::ShaderRead,
            },
        );
        let recorded = Arc::clone(&self.image_recorded);
        graph
            .add_copy_pass("ui-images")
            .use_image(page, ResourceState::TransferDst)
            .execute(move |ctx| {
                let image = ctx.image(page);
                ctx.encoder().copy_buffer_to_image(&BufferImageCopy {
                    buffer: upload.staging,
                    buffer_offset: 0,
                    buffer_row_length: upload.row_texels,
                    buffer_image_height: upload.rect.height,
                    image,
                    image_subresource: ImageSubresourceLayers {
                        aspect: ImageAspect::COLOR,
                        mip: 0,
                        base_layer: 0,
                        layer_count: 1,
                    },
                    image_offset: Offset3d {
                        x: upload.rect.x as i32,
                        y: upload.rect.y as i32,
                        z: 0,
                    },
                    image_extent: Extent3d::d2(upload.rect.width, upload.rect.height),
                });
                recorded.store(true, Ordering::Relaxed);
            });
        Some(page)
    }

    /// Adds one half of the draw list as one render pass, or nothing if the
    /// half is empty.
    ///
    /// Both halves index the *same* vertex and index buffers — the shader reads
    /// `vertices[SV_VertexID]` and the index values are absolute — so a half is
    /// a range of the frame's one upload rather than a second one.
    ///
    /// `pages` are the image atlas and the glyph pages, each when this frame's
    /// graph imported it for an upload, and the pass then declares that it
    /// samples it, so the graph returns it from the copy's `TransferDst` before
    /// the draw reads it. Every image of `textures` a draw of this half samples
    /// is declared the same way, which is what orders the pass that wrote it
    /// first.
    ///
    /// **One draw per bind of set 1** — see [`textures::draws`]: a half with no
    /// texture run in it is the one draw it always was.
    fn add_segment<'a>(
        &'a self,
        graph: &mut RenderGraph<'a>,
        segment: Segment,
        pages: [Option<ImageId>; 2],
        textures: &[UiTexture],
    ) {
        let Segment {
            target,
            extent,
            label,
            indices,
        } = segment;
        if indices.is_empty() {
            return; // nothing to draw
        }

        let pipeline = self.pipeline;
        let pipeline_layout = self.pipeline_layout;
        let bg = self.frame_groups[self.frame];
        let index_buffer = self.index_buffers[self.frame];
        let constants = self.constant_buffers[self.frame];
        let slot = self.frame;
        let texture_layout = self.texture_layout;
        let blank_group = self.blank_group;
        let groups = &self.texture_groups;

        // Each draw with the image it samples, resolved now, while the caller's
        // pairing is in hand; the view behind the image is the graph's to
        // realise, so that waits for the body.
        let planned: Vec<(Range<u32>, Option<ImageId>)> =
            draws(indices, &self.last_texture_runs[self.frame])
                .into_iter()
                .map(|draw| {
                    let image = draw.texture.and_then(|id| image_of(textures, id));
                    (draw.indices, image)
                })
                .collect();

        let mut pass = graph
            .add_render_pass(label)
            // Draw on top of the tonemapped target with alpha blending.
            .color(target, LoadOp::Load, StoreOp::Store, Default::default());
        for page in pages.into_iter().flatten() {
            pass = pass.read_image(page);
        }
        let mut sampled: Vec<ImageId> = Vec::new();
        for image in planned.iter().filter_map(|(_, image)| *image) {
            if !sampled.contains(&image) {
                sampled.push(image);
                pass = pass.read_image(image);
            }
        }
        pass.execute(move |ctx| {
            let block = UiConstants {
                viewport: [extent.0 as f32, extent.1 as f32],
            };
            let bytes: &[u8] = bytemuck::bytes_of(&block);
            // A host-visible write, not a command: it lands before this
            // frame is submitted, and the buffer is one of
            // `FRAMES_IN_FLIGHT` — the same rotation that makes the vertex
            // ring safe makes this safe.
            if let Err(error) = ctx.device().write_buffer(constants, 0, bytes) {
                // Recording a pass that draws nothing beats aborting the
                // frame, as in the tonemap's bind-group path: the HUD
                // vanishes for a frame, the log says why, the next frame
                // retries.
                crcbl_core::log::error!("graph: ui constants write failed: {error}");
                return;
            }
            // A group the device refused skips its draw and nothing else, as
            // `crcbl_render::bind_group_cache` skips a pass; the log says why.
            let bound: Vec<(Range<u32>, BindGroupHandle)> = planned
                .into_iter()
                .filter_map(|(range, image)| {
                    let group = match image {
                        None => blank_group,
                        Some(image) => {
                            let view = ctx.image_view(image);
                            groups.group(ctx.device(), texture_layout, slot, view)?
                        }
                    };
                    Some((range, group))
                })
                .collect();
            let encoder = ctx.encoder();
            encoder.bind_graphics_pipeline(pipeline);
            encoder.bind_group(0, bg, &[], pipeline_layout);
            encoder.bind_index_buffer(index_buffer, 0, IndexFormat::Uint32);
            let mut current = None;
            for (range, group) in bound {
                if current != Some(group) {
                    encoder.bind_group(TEXTURE_SET, group, &[], pipeline_layout);
                    current = Some(group);
                }
                encoder.draw_indexed(range, 0, 0..1);
            }
        });
    }

    /// Destroys all GPU resources.
    ///
    /// The device must be idle.
    pub fn destroy(mut self, device: &dyn Device) {
        if self.destroyed {
            return;
        }
        self.destroyed = true;
        for bg in self.frame_groups.drain(..) {
            device.destroy_bind_group(bg);
        }
        for vb in self.vertex_buffers.drain(..) {
            device.destroy_buffer(vb);
        }
        for ib in self.index_buffers.drain(..) {
            device.destroy_buffer(ib);
        }
        for cb in self.constant_buffers.drain(..) {
            device.destroy_buffer(cb);
        }
        for staging in self.image_staging.drain(..).flatten() {
            device.destroy_buffer(staging);
        }
        for staging in self.glyph_staging.drain(..).flatten() {
            device.destroy_buffer(staging);
        }
        self.texture_groups.destroy(device);
        device.destroy_bind_group(self.blank_group);
        self.blank.destroy(device);
        self.glyph_pages.destroy(device);
        device.destroy_sampler(self.atlas_sampler);
        self.atlas.destroy(device);
        device.destroy_sampler(self.image_sampler);
        self.image_page.destroy(device);
        device.destroy_graphics_pipeline(self.pipeline);
        device.destroy_pipeline_layout(self.pipeline_layout);
        device.destroy_bind_group_layout(self.bind_group_layout);
        device.destroy_bind_group_layout(self.texture_layout);
    }
}

impl Drop for UiRenderer {
    fn drop(&mut self) {
        if !self.destroyed {
            crcbl_core::log::warn!(
                "UiRenderer dropped without calling destroy() — GPU resources leaked"
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// What a partly-built [`UiRenderer`] has to give back.
///
/// `build` creates a dozen objects with `?` between them and the seam's
/// `destroy_*` is explicit, so a failure half way through would otherwise leak
/// everything created before it — a glyph atlas and two rings per failed
/// start-up. `crcbl_render::forward` carries the same shape for the same reason.
#[derive(Default)]
struct Rollback {
    buffers: Vec<BufferHandle>,
    bind_groups: Vec<BindGroupHandle>,
    bind_group_layouts: Vec<BindGroupLayoutHandle>,
    pipeline_layouts: Vec<PipelineLayoutHandle>,
    pipelines: Vec<GraphicsPipelineHandle>,
    samplers: Vec<SamplerHandle>,
    textures: Vec<UploadedTexture>,
}

impl Rollback {
    /// Releases everything, in the same dependency order as
    /// [`UiRenderer::destroy`].
    fn run(self, device: &dyn Device) {
        for handle in self.bind_groups {
            device.destroy_bind_group(handle);
        }
        for handle in self.buffers {
            device.destroy_buffer(handle);
        }
        for handle in self.samplers {
            device.destroy_sampler(handle);
        }
        for texture in self.textures {
            texture.destroy(device);
        }
        for handle in self.pipelines {
            device.destroy_graphics_pipeline(handle);
        }
        for handle in self.pipeline_layouts {
            device.destroy_pipeline_layout(handle);
        }
        for handle in self.bind_group_layouts {
            device.destroy_bind_group_layout(handle);
        }
    }
}

/// One half of the draw list, as [`UiRenderer::add_segment`] adds it: the
/// target and its extent, the pass's label, and the half's indices.
struct Segment {
    target: ImageId,
    extent: (u32, u32),
    label: &'static str,
    indices: Range<u32>,
}

/// One frame's staged image-atlas copy: where the bytes are and where they go.
#[derive(Clone, Copy, Debug)]
struct ImageUpload {
    staging: BufferHandle,
    rect: TexelRect,
    /// The staged rows' pitch, in texels.
    row_texels: u32,
}

/// One frame's staged glyph page copy.
#[derive(Clone, Copy, Debug)]
struct GlyphUpload {
    staging: BufferHandle,
    /// The page, which is the layer copied into.
    page: u32,
    rect: TexelRect,
    /// The staged rows' pitch, in texels.
    row_texels: u32,
}

/// The textures a frame's bind group names: the two atlases each as its view
/// and sampler, and the glyph pages, which share the bitmap font's sampler.
///
/// One argument rather than loose handles, so the pairs cannot be crossed at
/// the call site — a glyph view under the image sampler still binds.
#[derive(Clone, Copy)]
struct FrameTextures {
    glyphs: (ImageViewHandle, SamplerHandle),
    images: (ImageViewHandle, SamplerHandle),
    glyph_pages: ImageViewHandle,
}

/// One frame's bind-group entries.
///
/// One function rather than the two copies `new` and `begin_frame` used to
/// carry: they build the *same* group, and a binding added to one and forgotten
/// in the other is a bind group that stops matching its layout the first time
/// the vertex ring grows.
fn frame_entries(
    textures: FrameTextures,
    vertices: BufferHandle,
    constants: BufferHandle,
) -> [BindGroupEntry; 7] {
    [
        BindGroupEntry {
            binding: 0,
            array_index: 0,
            resource: BindingResource::ImageView(textures.glyphs.0),
        },
        BindGroupEntry {
            binding: 1,
            array_index: 0,
            resource: BindingResource::Sampler(textures.glyphs.1),
        },
        BindGroupEntry {
            binding: 2,
            array_index: 0,
            resource: BindingResource::whole_buffer(vertices),
        },
        BindGroupEntry {
            binding: CONSTANTS_BINDING,
            array_index: 0,
            resource: BindingResource::whole_buffer(constants),
        },
        BindGroupEntry {
            binding: IMAGE_ATLAS_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(textures.images.0),
        },
        BindGroupEntry {
            binding: IMAGE_SAMPLER_BINDING,
            array_index: 0,
            resource: BindingResource::Sampler(textures.images.1),
        },
        BindGroupEntry {
            binding: GLYPH_PAGES_BINDING,
            array_index: 0,
            resource: BindingResource::ImageView(textures.glyph_pages),
        },
    ]
}

fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
    shader.entry_point(stage).ok_or_else(|| {
        HalError::ShaderCompilation(format!(
            "{}.slang exposes no unambiguous {stage:?} entry point",
            shader.name()
        ))
    })
}

// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests;

#[cfg(all(test, not(target_arch = "wasm32")))]
mod texture_tests;