concinnity-device 0.19.23

GPU backends (Metal, Vulkan, DirectX) behind a device facade for Concinnity
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
#![deny(unsafe_op_in_unsafe_fn)]

use objc2::rc::Retained;
use objc2::runtime::ProtocolObject;
use objc2_metal::{
    MTLArgumentEncoder, MTLBuffer, MTLCommandBuffer as _, MTLCommandQueue, MTLDepthStencilState,
    MTLDevice as _, MTLIndirectCommandBuffer, MTLIndirectCommandBufferDescriptor,
    MTLIndirectCommandType, MTLPixelFormat, MTLRenderPipelineState, MTLResourceOptions,
    MTLSamplerState, MTLTexture,
};
use objc2_metal_kit::MTKView;

use crate::gfx::render_types::{
    ClusterParams, DrawObject, InstancedCluster, LightUniforms, NUM_SHADOW_CASCADES, ShadowUniforms,
};

use super::allocator::{DeviceAllocator, PooledBuffer, PooledTexture};
use super::auto_exposure::AutoExposureGpu;
use super::cull::CullState;
use super::decal::DecalState;
use super::fog::FogState;
use super::line::LineState;
use super::particle::ParticleState;
use super::post::{
    BloomPipelines, BloomTargets, GBufferState, SsaoState, SsgiState, SsrState, TaaState,
    UpscaleState,
};
use super::raytrace::RtState;
use super::resources::skinning::SkinnedState;
use super::texture::{EnvironmentMapTextures, HdrTargets};
use super::transient_pool::TransientTexturePool;

// MSAA sample count for the off-screen HDR target. Matches the sample
// count used pre-post-process (4×). Kept explicit here so all the
// pipelines that target the HDR buffer can reference the same constant.
pub(super) const HDR_SAMPLE_COUNT: u32 = 4;

// Size of the bindless texture pool the static main pass samples. The pool
// holds every albedo texture followed by every normal map; `GpuObjectData`
// carries pool indices into it. Must match `BINDLESS_TEXTURE_COUNT` in
// `main_bindless.slang`. Worlds with more than this many textures fall back to
// clamped indices (logged once at init).
pub(super) const BINDLESS_TEXTURE_COUNT: usize = 1024;

// Fragment buffer index the bindless static pass binds its `BindlessTextures`
// argument buffer at. Discrete `[[texture(n)]]` bindings make a fragment
// shader unusable from an indirect command buffer on Apple GPUs, so the
// texture pool + shadow/IBL maps travel in an argument buffer instead. Must
// match the buffer(7) slot of the engine fragment in `src/shaders/
// main_bindless.slang` (locked by the build script's ABI assertion) and of
// every world-authored bindless fragment.
pub(super) const BINDLESS_TEXTURE_ARG_BUFFER_INDEX: usize = 7;

// Fragment buffer index of the engine sampler block: indirect-command
// execution cannot see encoder-bound sampler state, so the engine's
// single-source fragment reads its three static samplers from this argument
// buffer. World-authored fragments declare inline samplers and ignore it.
pub(super) const BINDLESS_SAMPLER_ARG_BUFFER_INDEX: usize = 10;

// Stores the NSView* pointer set by cn_preview_start before world.start() is called.
// MtlContext::new() atomically takes it: non-null → embedded mode, null → windowed mode.
static EMBEDDED_VIEW_PTR: std::sync::atomic::AtomicPtr<std::ffi::c_void> =
    std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());

// Whether the next MtlContext should pump NSEvents in draw_frame even when in
// embedded mode. Preview leaves this false (the host owns input dispatch); the
// blocking-in-view play path sets it true so the world receives keyboard/mouse.
static EMBEDDED_PUMP_EVENTS: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

/// Called by cn_preview_start to register the NSView that MtlContext should embed into.
pub fn set_preview_view(ptr: *mut std::ffi::c_void) {
    EMBEDDED_VIEW_PTR.store(ptr, std::sync::atomic::Ordering::SeqCst);
}

/// Called by cn_run_world_blocking_in_view to opt the next embedded MtlContext
/// into pumping NSEvents (so the world receives input). The flag is consumed
/// in MtlContext::new and reset to false, so subsequent previews stay quiet.
pub fn set_embedded_pump_events(v: bool) {
    EMBEDDED_PUMP_EVENTS.store(v, std::sync::atomic::Ordering::SeqCst);
}

pub(super) fn take_embedded_view() -> *mut std::ffi::c_void {
    EMBEDDED_VIEW_PTR.swap(std::ptr::null_mut(), std::sync::atomic::Ordering::SeqCst)
}

pub(super) fn take_embedded_pump_events() -> bool {
    EMBEDDED_PUMP_EVENTS.swap(false, std::sync::atomic::Ordering::SeqCst)
}

// The scene draw list and the record counts that extend the GPU-driven cull
// past the static objects.
pub(super) struct DrawState {
    // One entry per renderable object.
    pub objects: Vec<DrawObject>,
    // The frame graph last compiled, keyed by the `FrameGraphInputs` it was
    // built from. `build_frame_graph` is a pure function of those inputs (which
    // change only when a feature toggles or a target resizes), so a frame whose
    // inputs match the cached key reuses it instead of rebuilding. Taken out
    // during `execute_graph` (which needs `&mut self`) and put back after, so a
    // steady scene compiles once.
    pub graph_cache: Option<(
        crate::gfx::render_graph::FrameGraphInputs,
        crate::gfx::render_graph::CompiledGraph,
    )>,
    // Total instances across every cluster. Each instance is folded into the
    // GPU-driven cull buffers as an extra `GpuObjectData` record after the
    // static objects, so the cull dispatch + indirect draw cover
    // `cull_count() == objects.len() + draw.n_instances`.
    pub n_instances: usize,
    // Skinned draw objects folded into the GPU-driven cull, set by
    // `upload_skinned`. Each is one extra `GpuObjectData` record after the
    // static + instance records, so `cull_count()` extends to
    // `objects.len() + draw.n_instances + draw.n_skinned` and the skinned tail
    // draws the compute-deformed geometry through the skinned index buffer.
    pub n_skinned: usize,
}

// InstancedProp clusters and the per-instance records they draw through.
pub(super) struct InstancedState {
    // One entry per cluster. Each issues one drawIndexedInstanced call with all
    // of its per-instance transforms uploaded to a transient GPU buffer per
    // frame. Empty when there are no clusters in the scene.
    pub clusters: Vec<InstancedCluster>,
    // The per-instance `GpuObjectData` / `GpuDrawArgs` records, built once at
    // init (instances are placed at world load and never move).
    // `build_object_buffer` / `build_draw_args_buffer` append these after their
    // per-frame static fill, so the transient object / draw-args rings carry
    // both. `draw_args` carries each cluster's base LOD slice; the per-frame
    // build patches the instances of clusters that declare alternates.
    pub records: Vec<crate::gfx::render_types::GpuObjectData>,
    pub draw_args: Vec<crate::gfx::render_types::GpuDrawArgs>,
    // Whether any cluster declares LOD alternates. False skips the per-frame
    // per-instance LOD pass entirely: without alternates the base slice above
    // is the right answer for every instance, for the life of the world.
    pub any_lod: bool,
}

// The frame's view state, snapped from `FrameParams` at the top of `draw_frame`.
pub(super) struct ViewState {
    pub clear_color: [f32; 4],
    // Scene-transition fade to black in [0, 1], applied in the composite pass.
    // Backend-owned rather than a `PostProcessParams` field so a settings push
    // cannot reset an in-flight fade, and kept out of `view.clear_color` so it fades
    // the whole image, not just the pixels no geometry covers.
    pub scene_fade: f32,
    // The viewport view mode: the main passes read it for the wireframe fill
    // mode and the unlit shade flag, the composite for its channel
    // visualization.
    pub mode: concinnity_core::gfx::view_modes::ViewMode,
    // The frame's camera far plane, for the composite's depth-channel
    // normalization.
    pub far: f32,
    pub matrix: [[f32; 4]; 4],
    // Rows of the sky's inverse rotation, uploaded into every uniform block
    // whose pass samples the environment cubemaps.
    pub sky_rot: [[f32; 4]; 3],
}

// Scene-captured reflection probes: each surface's specular reflection samples
// the nearest probe whose box contains it, while the skybox + diffuse keep the
// sky. See metal/probe.rs.
pub(super) struct ProbeState {
    // The where/box list (declared `ReflectionProbe` assets or
    // `auto_seed_probes`).
    pub placements: Vec<crate::gfx::reflection_probe::ProbePlacement>,
    // The baked cube per placement, parallel to `placements`.
    pub maps: Vec<ProbeCube>,
    // Staggered bake cursor. Reset to the placement count when placements are
    // set; each eligible frame bakes a bounded budget and advances it, so the
    // load cost spreads over several frames instead of one.
    pub bake_queue: crate::gfx::reflection_probe::ProbeBakeQueue,
    // Per-probe influence boxes + count, pushed to the fragment shader at
    // buffer(6). `EMPTY` until a bake.
    pub set: concinnity_core::render::uniforms::ProbeSet,
    // The probe currently rendering its six cube faces on the GPU (one at a
    // time; owns the reserved-ring-slot buffers + capture targets). The render
    // thread never blocks: the faces are submitted without `waitUntilCompleted`
    // and a completion handler flags GPU completion. `None` when idle.
    pub rendering: Option<super::probe::RenderingBake>,
    // The probe whose capture is convolving into its cube on the GPU (one at a
    // time), one destination mip per frame. It overlaps the next probe's render,
    // which shortens the bake warm-up. `None` when idle.
    pub prefiltering: Option<super::probe::PrefilteringBake>,
    // The three convolution kernels, built at init under the same gate the bake
    // needs (the bindless cull pipeline). `None` disables baking.
    pub prefilter: Option<super::probe_prefilter::ProbePrefilterPipelines>,
    // Deferred-free pool for an in-flight bake's GPU resources when a
    // re-placement (`set_reflection_probes`) interrupts it: the capture command
    // buffers may still be reading those buffers/textures, so they are parked
    // here and freed once the frames-in-flight fence guarantees the bake has
    // retired.
    pub retire_pool: super::transient::RetirePool<super::probe::RetiredBake>,
    // This frame's `ProbeCubes` argument buffer, written by
    // `build_probe_cube_args` and bound by every pass that samples the cubes.
    // `None` before the first frame builds one.
    pub cube_args: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
}

// One baked reflection probe: the prefiltered radiance cube the specular term
// samples. No irradiance cube -- a probe feeds specular only, and the diffuse
// term keeps sampling `env_map`.
pub(super) struct ProbeCube {
    pub prefilter: super::allocator::PooledTexture,
}

// Cascaded shadow map resources + the cascade schedule. `pipeline_state` is
// `None` when no ShadowStage was declared or `map_size == 0`, in which case the
// shadow pass is skipped; `map` and `sampler` are always present (1x1 fallback
// reading 1.0 = fully lit when disabled) so fragment shaders can always sample
// texture(2) / sampler(1). Mirrors `DxContext::shadow`.
pub(super) struct ShadowState {
    pub pipeline_state: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    // Depth32Float texture array, one slice per cascade.
    pub map: Retained<ProtocolObject<dyn MTLTexture>>,
    // Per-cascade resolution, stored so the shadow pass can size the viewport to
    // the texture array's per-slice dimensions.
    pub map_size: u32,
    // Cascade re-render policy from `GraphicsConfig.shadow_update`. Hybrid
    // refreshes the near cascade every frame and the far cascades round-robin.
    pub update: crate::components::ShadowUpdate,
    // Shadow distance in world units (`GraphicsConfig.shadow_distance`), read by
    // the per-frame cascade-split computation and capped at the camera far
    // plane. Mutable so `set_shadow_distance` can change it live.
    pub distance: u32,
    // Active cascade count, 1..=4 (`GraphicsConfig.shadow_cascades`). The
    // per-frame split + schedule read it; only the first `cascades` of the four
    // slots are rendered + sampled. Mutable so `set_shadow_cascades` is live.
    pub cascades: u32,
    // Round-robin clock + primed-set for the cascade schedule; advanced once per
    // frame by `next_shadow_cascade_mask`.
    pub scheduler: crate::gfx::shadow_schedule::ShadowCascadeScheduler,
    // Cascades re-rendered this frame (bit `i` = cascade `i`). Computed in
    // draw_frame and read by encode_shadow_pass so the two agree on which slices
    // to refresh and which to leave intact.
    pub render_mask: u32,
    pub sampler: Retained<ProtocolObject<dyn MTLSamplerState>>,
    // Cascaded light VPs + split depths. The near cascade's VP refreshes every
    // frame; far cascades' VPs persist between their round-robin refreshes
    // (Hybrid mode) so each slice is sampled with the VP it was rendered with.
    pub uniforms: ShadowUniforms,
    // World-space unit vector pointing TOWARD the first directional light.
    // Captured at init from the light uniforms; used by per-frame CSM updates.
    pub light_dir: [f32; 3],
}

// Spot-light shadow slices + their refresh schedule. Mirrors
// `DxContext::spot_shadow`.
pub(super) struct SpotShadowState {
    // One Depth32Float slice per shadow-casting spot light, indexed by
    // `GpuLight.shadow_index`. Always present so the fragment shader's
    // depth-array binding is valid; a 1x1 fallback (depth 1.0 = lit) stands in
    // when no spot casts shadows.
    pub map: Retained<ProtocolObject<dyn MTLTexture>>,
    // Per-slice light-space projections, uploaded once (local lights are
    // static). Empty when nothing casts, in which case the pass never runs.
    pub buffer: PooledBuffer,
    pub count: u32,
    // Prime-then-round-robin refresh schedule over the spot slices, the spot
    // analogue of `ShadowState::scheduler`.
    pub scheduler: crate::gfx::spot_shadow::SpotShadowScheduler,
    // Which spot slices re-render this frame; set once per frame in draw_frame
    // and read by encode_spot_shadow_pass.
    pub render_mask: u32,
}

// Per-frame-in-flight transient buffer rings, plus the CPU scratch that fills
// them. Each ring hands out this frame's slot so a build reuses a buffer instead
// of allocating one per frame; the scratch `Vec`s are `mem::take`n during a build
// and returned after, so the per-frame `collect` reuses one heap allocation.
pub(super) struct FrameRings {
    // Ring of per-frame `GpuObjectData` buffers. Written by `build_object_buffer`.
    pub object: super::transient::TransientRing,
    // Ring of per-frame `GpuDrawArgs` buffers for the GPU-cull pass. Written by
    // `build_draw_args_buffer`.
    pub draw_args: super::transient::TransientRing,
    // Ring of per-frame model-history buffers for the GPU-driven G-buffer /
    // velocity pre-pass: one column-major `float4x4` per cull record, indexed
    // identically to the object buffer. Filled on the GPU by
    // `encode_model_history`; frame `R` reads the slot frame `R - 1` wrote.
    pub model_history: super::transient::TransientRing,
    // Ring of per-frame `BindlessTextures` argument buffers. The argument
    // encoder fills the slot in place each frame; see
    // `build_bindless_texture_args`.
    pub bindless_tex: super::transient::TransientRing,
    // Ring of per-frame `ProbeCubes` argument buffers, written by
    // `build_probe_cube_args`.
    pub probe_cube: super::transient::TransientRing,
    // Ring of per-skinned-object joint-palette buffers, one inner buffer per
    // object. Written by `build_joint_buffers`.
    pub joint: super::transient::JointRing,
    pub object_scratch: Vec<crate::gfx::render_types::GpuObjectData>,
    pub draw_args_scratch: Vec<crate::gfx::render_types::GpuDrawArgs>,
}

// Transparent water surfaces and the pipelines that draw them. The RT variants
// trace a sharp reflection ray against the scene BVH instead of sampling the
// probe cube; they are `Some` only when the world has >=1 `WaterSurface` AND the
// device supports ray tracing, and are selected per-frame only while `rt.accel`
// is live. The flat variant uses the per-object material tint as albedo (the
// non-bindless RT fallback); the textured variant samples the reflected hit's
// albedo / normal / emissive maps from the bindless pool (bound at buffer 10 for
// water, since the main pass's index 7 is the ProbeSet here) and is selected
// only in a bindless world.
pub(super) struct WaterState {
    // `Some` only when the world declared >=1 `WaterSurface`; the transparent
    // pass executor short-circuits otherwise.
    pub pipeline: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    pub pipeline_rt: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    pub pipeline_rt_textured: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    // One GPU record per `WaterSurface` asset: tessellated VB+IB plus the
    // per-surface fragment / vertex uniforms, built once at init from the
    // asset.
    pub surfaces: Vec<super::water::WaterSurfaceRecord>,
}

// Transparent glass: the `GlassPanel` producer and the see-through mesh path.
// The panel RT variants follow the same flat / textured split as [`WaterState`].
pub(super) struct GlassState {
    // Shared pipeline for the `GlassPanel` transparent producer. `Some` only
    // when the world declared >=1 `GlassPanel`.
    pub pipeline: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    pub pipeline_rt: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    pub pipeline_rt_textured: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    // Ray-traced see-through glass MESH pipelines (`glass_mesh.slang`): an
    // imported `Material` with `transparent: true` routed through the transparent
    // pass with a per-pixel RT trace off the interpolated mesh normal, instead of
    // the Layer-1 opaque-reflective fallback. Built only on RT-capable devices
    // (regardless of whether the world declares a transparent material -- a live
    // RT toggle then has the pipeline ready). `mesh_pipeline_rt.is_some()` gates
    // the whole transparent-mesh path: when live (RT on) transparent meshes are
    // skipped in the opaque pass + the RT BLAS and drawn here; otherwise they
    // render opaque (Layer 1).
    pub mesh_pipeline_rt: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    pub mesh_pipeline_rt_textured: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    // Indices into `draw.objects` of every see-through glass mesh (its material
    // has both `transparent` and `see_through` set), precomputed at init so the
    // per-frame Layer 2 producer does not rescan all objects. Empty on non-RT
    // devices or when no material opts into see-through (those transparent meshes
    // then render opaque, Layer 1). The objects stay IN `draw.objects` (a
    // DrawObject's position is a key into the cull / prev-model / RT parallel
    // arrays); this list only marks which to reroute. A non-empty list (plus a
    // built mesh pipeline) is what enables the Layer 2 path -- see
    // `seethrough_meshes_enabled`. See-through is opt-in per `Material` because
    // it only looks right when the space behind the glass is modelled; without
    // it, Layer 1's tinted reflective glass hides the interior.
    pub seethrough_mesh_indices: Vec<usize>,
    // One GPU record per `GlassPanel` asset: the static world-space quad VB+IB
    // plus the per-panel uniforms. Contributes to the transparent pass.
    pub panels: Vec<super::glass::GlassPanelRecord>,
}

// Raymarched SDF volumes and the unit-cube proxy geometry the pass rasterises.
pub(super) struct RaymarchState {
    // One GPU record per `SdfVolume` asset: the per-volume render pipeline
    // (compiled lazily at init from the user's fragment shader source + the
    // engine-shipped helpers/template) plus the static per-volume uniforms
    // (centre, extent, params, ...). Drives the pass at `PassId::Raymarch`.
    pub volumes: Vec<super::raymarch::RaymarchVolumeRecord>,
    // Shared unit-cube proxy geometry (8 vertices, 36 indices). `Some` whenever
    // any `SdfVolume` exists in the world; the encoder reads them per-frame and
    // the asset cost is fixed (96 + 72 bytes).
    pub cube_vertex_buffer: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
    pub cube_index_buffer: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
}

// HUD text pass. `pipeline_state` is `None` when no Font assets were declared
// and `atlas_textures` is empty in the same case. The pipeline targets the
// single-sample drawable in the composite pass (after HDR tonemap), so text is
// rendered in display-referred LDR.
pub(super) struct TextState {
    pub pipeline_state: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    pub atlas_textures: Vec<PooledTexture>,
    // Linear-clamp sampler for glyph atlas lookups.
    pub sampler: Retained<ProtocolObject<dyn MTLSamplerState>>,
    // Ring of per-frame HUD text geometry buffers. `draw_frame` writes the whole
    // frame's labels into this frame's slot before the graph runs; the composite
    // pass binds sub-ranges of it.
    pub upload: super::text_upload::TextUploadRing,
}

// Built-in shader hot reload. `enabled` is true only under `cn debug`: it
// switches the built-in `.metal` source loader to a disk-first read with
// embedded fallback, so a saved shader edit is picked up by
// [`MtlContext::reload_shaders`]. Under `cn run` production keeps the static
// `include_str!`-baked path. `reload_pending` is the atomic flag set by the
// `notify` watcher or the debug WS `reload-shaders` command, polled at the top of
// `draw_frame`; the debug server reads its `Arc` clone via `GraphicsSystem`.
// Both it and `watcher` are `Some` only when `enabled`.
pub(super) struct HotReloadState {
    pub enabled: bool,
    pub reload_pending: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    // Held purely for lifetime: dropping it stops the watcher, which pushes
    // events into `reload_pending` directly rather than being read from here.
    #[expect(
        dead_code,
        reason = "held so the watcher thread stays alive; events arrive through reload_pending"
    )]
    pub watcher: Option<crate::metal::hot_reload::WatcherHandle>,
}

// Byte-range sub-allocators over the shared `vertex_buffer` / `index_buffer`.
// The mesh pair covers the streamed-mesh regions, seeded at init by evicting
// every streamed mesh; from then on `upload_mesh` / `evict_mesh` allocate and
// free byte ranges so a streamed mesh can be placed wherever there is free
// space. The chunk pair covers the headroom region appended by
// `setup_chunk_streaming`, disjoint from both the build-time geometry and the
// mesh allocators so a streamed `VoxelWorld` chunk never collides with static
// geometry; empty until `setup_chunk_streaming` runs.
pub(super) struct GeometryAllocators {
    pub mesh_vtx: crate::suballoc::range_alloc::RangeAllocator,
    pub mesh_idx: crate::suballoc::range_alloc::RangeAllocator,
    pub chunk_vtx: crate::suballoc::range_alloc::RangeAllocator,
    pub chunk_idx: crate::suballoc::range_alloc::RangeAllocator,
}

// The window this context draws into.
pub(super) struct WindowState {
    // The shared AppKit window + input layer (crate::appkit), which also owns the
    // NSWindow, the fullscreen tracking, and the display-mode hold. Holds the
    // same view as `view` below, upcast to `NSView`.
    pub appkit: crate::appkit::AppKitWindow,
    // MTKView with isPaused=true and enableSetNeedsDisplay=false so its internal
    // display link never fires. draw() is called manually from draw_frame().
    // Metal-only: the drawable and its render-pass descriptor come from here,
    // which is why the shared window layer keeps only the NSView upcast.
    pub view: Retained<MTKView>,
    // Whether this context is responsible for tearing the window / view down on
    // drop (closing the NSWindow, or removing the embedded subview). True for a
    // normally constructed context; set false on the outgoing context of a live
    // `cn editor` reload, which transplants the window to its successor -- the
    // successor owns it now, so the outgoing drop must NOT close the shared
    // window (that would order it out from under the reused context).
    pub owns: bool,
    pub was_visible: bool,
}

// Per-frame counters, GPU timings, and the fault reporting that crosses the
// backend boundary. Most of these are written from a GPU completion handler on a
// callback thread, so they are shared behind atomics.
pub(super) struct Diagnostics {
    // Per-frame draw-call / VRAM / GPU-time counters surfaced to the profiler
    // overlay via `render_stats`.
    pub frame_stats: crate::gfx::profile::RenderStats,
    // GPU execution time of the last completed frame, in microseconds. Written
    // by each command buffer's completion handler.
    pub gpu_time_us: std::sync::Arc<std::sync::atomic::AtomicU32>,
    // Set once the frame render command buffer is observed to have faulted on
    // the GPU. A render fault is the usual *origin* of a `SubmissionsIgnored`
    // cascade that then shows up downstream on the next acceleration-structure
    // build; logging the render buffer's own error names the real culprit.
    // Logged once (this flag throttles it) so a per-frame fault streak does not
    // spam at frame rate.
    pub render_fault_logged: std::sync::Arc<std::sync::atomic::AtomicBool>,
    // First classified GPU failure observed on a completed frame command buffer,
    // parked here by the completion handler until the next draw_frame reports it
    // across the backend boundary.
    pub device_error: std::sync::Arc<std::sync::Mutex<Option<crate::gfx::error::RenderError>>>,
    // Count of render-graph per-pass command-buffer faults logged so far. Each
    // graph pass commits its own command buffer; this throttle logs the first
    // handful (with the pass name + error) so the *original* fault in a
    // `SubmissionsIgnored`/`InnocentVictim` cascade is identifiable, while later
    // victims do not spam at frame rate.
    pub pass_fault_count: std::sync::Arc<std::sync::atomic::AtomicU32>,
    // Per-pass GPU sample buffers, when the active device supports the
    // `MTLCommonCounterSetTimestamp` counter set. Each `draw_frame` rotates to
    // the next slot in the ring; the completion handler resolves that slot into
    // `diagnostics.pass_times_us` for the profiler overlay.
    pub pass_timing: Option<super::pass_timing::PassTimingResources>,
    // Per-pass GPU microseconds from the most recently resolved frame. One
    // atomic per pass slot, shared between the GPU completion handler that
    // writes it and `render_stats()` that reads it.
    pub pass_times_us:
        std::sync::Arc<[std::sync::atomic::AtomicU32; super::pass_timing::PASS_COUNT]>,
    // Atomic accumulator the parallel-dispatched workers fetch_add their draw
    // counts into. Drained into `diagnostics.frame_stats.draw_calls` at the end of
    // `execute_graph`. AtomicU32 because workers may run concurrently.
    pub draw_calls_accum: std::sync::atomic::AtomicU32,
}

// HDR output negotiation for the swapchain.
pub(super) struct HdrState {
    // Maximum extended-range colour-component multiplier reported by the active
    // panel when the renderer is on the HDR path. `Some(2.0)` on HDR400,
    // `Some(8.0+)` on HDR1000-class panels; `None` on SDR (whether the world
    // disabled HDR or the platform fell back). Surfaced via `RenderStats.max_edr`
    // so the `StatHud` overlay can render an `EDR` chip showing the headroom.
    pub max_edr: Option<f32>,
    // Resolved HDR encoding of the swapchain (scRGB-linear vs PQ), or `None` on
    // the SDR path. Read only by the headless `screenshot` path to decode the
    // captured `RGBA16Float` EDR drawable. Mirrors DX `hdr.encoding`.
    pub encoding: Option<crate::gfx::hdr_output::HdrEncoding>,
    // The world's HDR-output *request* this context was built with (before EDR
    // negotiation could fall it back to SDR). Reported by `hot_swap_config` so a
    // live `cn editor` world reload can tell whether the new world would produce
    // the same swapchain: comparing the request (not the negotiated result) keeps
    // a display without EDR headroom from spuriously forcing a rebuild every
    // save. Paired with `frames_in_flight` as the swapchain identity.
    pub display_requested: bool,
    pub pq_requested: bool,
}

// Metal rendering context. Owns all GPU resources and the window.
// Only ever accessed from the main thread.
pub(crate) struct MtlContext {
    pub(super) device: Retained<ProtocolObject<dyn objc2_metal::MTLDevice>>,
    // Block pool every persistent CPU-written, GPU-read-only buffer and texture
    // is placed in, so the world's resource count costs a handful of heaps
    // rather than one device allocation each. See `metal/allocator.rs`.
    pub(super) allocator: DeviceAllocator,
    pub(super) command_queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
    // Pixel format the MTKView's CAMetalLayer is currently presenting at:
    // `BGRA8Unorm` for SDR, `RGBA16Float` for HDR EDR. The post + text
    // pipelines bake this format into their colour attachment descriptors,
    // so it has to be stable between `MtlContext::new` and any subsequent
    // hot-reload rebuild. `swap_pixel_format == RGBA16Float` is the runtime
    // equivalent of `HdrOutputMode::is_hdr()`, and the per-frame
    // `PostProcessParams.hdr_output` flag carries the EDR signal into the
    // shader.
    pub(super) swap_pixel_format: MTLPixelFormat,
    pub(super) hdr: HdrState,
    // Colour texture of the most recently presented drawable, retained so the
    // `cn debug` `screenshot` command can blit it back to a host buffer and
    // PNG-encode it (see metal/screenshot.rs). Set each frame only under
    // `hot_reload` (the path that runs the WS server able to request a
    // capture); `None` in production and before the first present, so a
    // capture then returns a clean error. The MTKView has `framebufferOnly`
    // switched off under the same gate so the drawable is blit-readable.
    // Mirrors the DX/VK `last_present_index`.
    pub(super) last_present_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
    // Main-pass PBR pipeline. None for a world with no 3D scene content
    // (render requirements derived `scene == false`): the Main pass then
    // encodes as a bare clear and every geometry sub-path early-outs.
    pub(super) pipeline_state: Option<Retained<ProtocolObject<dyn MTLRenderPipelineState>>>,
    // Pipelines for the material-referenced world shaders, indexed by
    // `shader_bucket - 1` (bucket 0 is `pipeline_state`). Each executes its
    // bucket's ICB in the main pass; empty for single-shader worlds. `None`
    // while the bucket's Shader is not resident -- init defers a shader owned
    // by a scene other than the start scene, and `install_world_shader` builds
    // it when that scene pins. Draws carrying a `None` bucket are skipped.
    pub(super) world_pipelines: super::init::pipelines::WorldPipelineTable,
    // True when the GPU-driven main pass exists: a world with 3D scene
    // content. The static draw loop then reads each object from the per-frame
    // `GpuObjectData` buffer and the bindless texture pool. False for a world
    // with no scene content, whose Main pass is a bare clear.
    pub(super) bindless: bool,
    // GPU-driven cull feature state: the phase-1/phase-2 cull pipelines,
    // their indirect command buffers + argument encoders/buffers, the
    // per-object status buffer, the two-pass-occlusion toggle, and the Hi-Z
    // pyramid + view-projection snapshots the occlusion test reprojects
    // through. All `Some`/active only when the world has 3D scene content.
    // See [`CullState`].
    pub(super) cull: CullState,
    // Encoder that packs the bindless pass's textures into a per-frame
    // argument buffer (the `BindlessTextures` block). `Some` only
    // when `bindless`; the argument buffer itself is rebuilt every frame so
    // streamed texture swaps are picked up and the GPU never reads a buffer
    // the CPU is mid-rewrite. (A main-pass resource, not part of `cull`.)
    pub(super) bindless_tex_arg_encoder: Option<Retained<ProtocolObject<dyn MTLArgumentEncoder>>>,
    // Argument encoder for the `ProbeCubes` block the five probe-sampling
    // fragments declare; see `probe_cubes::probe_cube_arg_encoder`.
    pub(super) probe_cube_arg_encoder: Retained<ProtocolObject<dyn MTLArgumentEncoder>>,
    // The engine sampler block bound at fragment buffer(10) for the
    // single-source main program: three static samplers written once at init
    // (samplers never stream, so no per-frame ring is needed). `None` when a
    // world-authored fragment owns the main pass.
    pub(super) bindless_sampler_args: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
    pub(super) depth_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
    // Read-only depth state: `LessEqual` test, no write. Used by translucent
    // draws that must be occluded by nearer opaque geometry but must not
    // update the depth buffer (volumetric raymarch volumes). Metal forbids
    // `setDepthStencilState(nil)` under the validation layer, so translucent
    // passes bind this instead of clearing the state.
    pub(super) depth_state_read_only: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
    // Single shared vertex buffer containing geometry for all draw objects.
    pub(super) vertex_buffer: PooledBuffer,
    // Single shared index buffer containing indices for all draw objects.
    pub(super) index_buffer: PooledBuffer,
    // Draw list + cull inputs + folded record counts. See [`DrawState`].
    pub(super) draw: DrawState,
    // InstancedProp clusters. See [`InstancedState`].
    pub(super) instanced: InstancedState,
    // Per-frame view state. See [`ViewState`].
    pub(super) view: ViewState,
    // True when the world has no 3D geometry (e.g. a text-only world). The
    // off-screen HDR / bloom / effect targets are then allocated at 1x1 since
    // nothing is rendered into them; the composite pass still runs at the full
    // drawable size, so text stays crisp.
    pub(super) geometry_less: bool,
    // Shared texture pool (slot == handle): every texture (albedo, normal map,
    // emissive/ORM, terrain secondary) lives here once, matching DX/VK. A 1x1
    // opaque-white fallback is always present at slot 0 so shaders that sample
    // texture(0) produce correct output even when no Texture asset was declared.
    pub(super) textures: Vec<PooledTexture>,
    // Holds only the 1x1 flat-normal fallback (RGBA 128,128,255,255) a
    // normal-less draw samples; its pool slot is one past the last real texture.
    // Real normal maps are entries in `textures`.
    pub(super) fallback_textures: Vec<PooledTexture>,
    // All scene lights packed and pushed to the fragment shader at buffer(4).
    pub(super) light_uniforms: LightUniforms,
    // Per-scene local lights (point + spot + area) for the clustered forward
    // pass, bound at fragment buffer(8). Always holds at least one element (a
    // neutral placeholder when the scene declares no local lights) so the
    // binding is valid; `light_uniforms.num_local_lights` bounds iteration.
    pub(super) local_light_buffer: PooledBuffer,
    pub(super) sampler: Retained<ProtocolObject<dyn MTLSamplerState>>,
    // Cascaded shadow map + its schedule. See [`ShadowState`].
    pub(super) shadow: ShadowState,
    // Spot-light shadow slices + their schedule. See [`SpotShadowState`].
    pub(super) spot_shadow: SpotShadowState,
    // Per-scene rect area-light extents, indexed by `GpuLight.data_index`.
    // Uploaded once; a one-element placeholder when the world declares none.
    pub(super) area_light_buffer: PooledBuffer,
    // The two linearly-transformed-cosine lookup tables the area-light shading
    // path samples: the inverse transforms (RGBA32Float) and the matching
    // (albedo, Fresnel) pairs (RG32Float). Generated at build time, so these are
    // scene-independent and created once.
    pub(super) ltc_matrix_texture: PooledTexture,
    pub(super) ltc_magnitude_texture: PooledTexture,
    // IBL cubemaps + mip count. Always Some: the runtime synthesizes a 1x1
    // grey fallback for both cubes when no EnvironmentMap was supplied, so
    // the fragment shader's texture(3) / texture(4) bindings are always
    // valid. `prefilter_mip_count == 0` is the "IBL disabled" signal the
    // shader uses to fall back to the legacy ambient/skybox path.
    pub(super) env_map: EnvironmentMapTextures,
    // Local reflection probes: the scene captured into one cube per placement
    // (metal/probe.rs). Distinct from `env_map` (which stays the sky -- it drives
    // the skybox + diffuse irradiance) so the bake never corrupts the visible
    // sky. Each surface's specular reflection samples the nearest probe whose box
    // contains it; the skybox + diffuse keep the sky.
    //
    // Scene-captured reflection probes. See [`ProbeState`].
    pub(super) probe: ProbeState,
    // Linear-clamp sampler bound at sampler(2) for cubemap sampling.
    pub(super) cube_sampler: Retained<ProtocolObject<dyn MTLSamplerState>>,
    pub(super) text: TextState,
    // Off-screen HDR render targets (MSAA RGBA16Float + resolve + MSAA
    // Depth32Float). Re-created lazily in `draw_frame` whenever the
    // drawable size changes. The main + instanced pipelines render into
    // these, and the post-process pass samples `hdr_resolve` to write
    // the tonemapped + FXAA-filtered output into the drawable.
    pub(super) hdr_targets: HdrTargets,
    // Pipeline that performs ACES tonemap + gamma 2.2 + FXAA from the
    // resolved HDR target into the drawable.
    pub(super) post_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
    // Linear-clamp sampler bound at sampler(0) when sampling the HDR
    // resolve target during the post pass. Also reused by the bloom passes.
    pub(super) post_sampler: Retained<ProtocolObject<dyn MTLSamplerState>>,
    // Bloom mip chain (prefilter/downsample/upsample targets). Re-created
    // alongside `hdr_targets` whenever the drawable size changes.
    pub(super) bloom_targets: BloomTargets,
    // Prefilter / downsample / upsample pipelines for the bloom chain. None
    // for a world with no 3D scene content: the graph never inserts the Bloom
    // pass, and the composite's unconditional top-mip bind stays 1x1 black.
    pub(super) bloom_pipelines: Option<BloomPipelines>,
    // Pool backing the render graph's transient textures
    // (`gfx::render_graph::alias`). Owns `bloom_top` (which `bloom_targets`
    // borrows as mip 0) and, when SSAO is on, `ao_output`; their disjoint
    // lifetimes put them on one aliased `MTLHeap` slot. Rebuilt on resize. See
    // [`TransientTexturePool`].
    pub(super) transient_pool: TransientTexturePool,
    // Post-process tunables (bloom intensity / threshold / knee). Pushed to
    // the bloom prefilter and composite fragment shaders. `bloom_intensity`
    // of 0 skips the bloom passes entirely.
    pub(super) post_process: crate::gfx::render_types::PostProcessParams,
    // 3D colour-grading LUT sampled in the composite pass. Holds the declared
    // `ColorLut` payload, or a 2x2x2 identity LUT when the world declares
    // none, so the composite pass binds a valid 3D texture either way.
    pub(super) color_lut: PooledTexture,
    // Temporal-anti-aliasing feature state: the toggle, resolve pipeline,
    // ping-pong history buffers, and per-frame bookkeeping. See [`TaaState`].
    pub(super) taa: TaaState,
    // Previous frame's un-jittered view-projection, fed to the velocity
    // pre-pass to reproject motion. Identity until the first frame completes.
    // (Shared by both TAA and the upscaler when either drives the velocity
    // pre-pass, so it is kept flat rather than under `taa`.)
    pub(super) prev_view_proj: [[f32; 4]; 4],
    // MetalFX-temporal-upscaling feature state: the scaler, the input/output
    // scale ratio, the per-frame projection jitter, and the history-reset
    // flag. When the scaler is `Some`, the 3D scene renders at
    // `(output * upscale.scale)` and the scaler reconstructs a
    // drawable-resolution image the bloom + composite stack reads as
    // `scene_color`; the TAA pass is bypassed (the scaler accumulates
    // temporally), though the velocity pre-pass + projection jitter still
    // run. See [`UpscaleState`].
    pub(super) upscale: UpscaleState,
    // SSAO (GTAO) feature state: resolved tunables, occlusion targets, the
    // kernel + blur pipelines, and the 1×1 white fallback. See [`SsaoState`].
    pub(super) ssao: SsaoState,
    // Screen-space-reflection feature state: resolved tunables, the resolve
    // output target (shared with SSGI/RT), and the resolve pipeline. See
    // [`SsrState`].
    pub(super) ssr: SsrState,
    // Unified G-buffer pre-pass feature state: the shared normal+depth /
    // roughness / velocity / sampleable-depth targets plus the static /
    // instanced / skinned pipelines. See [`GBufferState`].
    pub(super) gbuffer: GBufferState,
    // Screen-space-GI feature state: resolved tunables, the `gi` gather
    // target, and the gather + composite pipelines. See [`SsgiState`].
    pub(super) ssgi: SsgiState,
    // Resolved + clamped ray-traced-reflection tunables. `Some` only when the
    // Hardware-ray-traced-reflection feature state: resolved tunables, the
    // scene acceleration structure, the dynamic-update mode + failure flag, and
    // the resolve / textured-resolve / skinning pipelines. See [`RtState`].
    pub(super) rt: RtState,
    // World-space line state (editor origin axes, collider previews):
    // the pipeline, built on the first frame that publishes lines. See
    // [`LineState`].
    pub(super) lines: LineState,
    // Projected-decal feature state: the decal slot table, the pipeline, the
    // shared unit-cube geometry, and the sampler. See [`DecalState`]. The pipeline / cube buffers / sampler are
    // built lazily at init (≥1 declared decal) or on the first runtime
    // [`MtlContext::add_decal`].
    pub(super) decal: DecalState,
    // Volumetric-fog feature state: resolved tunables, the ray-march
    // pipeline, and the froxel-volume compute pipeline + 3D output volume.
    // See [`FogState`].
    pub(super) fog: FogState,
    // Clustered-lighting state: the binning compute pipeline + the per-cluster
    // light-index buffer. See [`LightCullState`].
    pub(super) light_cull: super::light_cull::LightCullState,
    // Per-frame clustered-lighting params (main camera), rebuilt each frame in
    // draw_frame and bound to the light-cull pass + the forward pass. Mirrors
    // shadow.uniforms' per-frame update + shared bind.
    pub(super) cluster_params: ClusterParams,
    // Particle-system feature state: the per-emitter records (+ tombstone
    // free-list), the parallel per-emitter GPU pools, the shared compute +
    // render pipelines, and the per-frame timing bookkeeping. See
    // [`ParticleState`].
    pub(super) particle: ParticleState,
    // Auto-exposure feature state: resolved tunables, the EMA-tracked adapted
    // EV + authored bias, the histogram/average compute pipelines + buffers,
    // and the per-frame timing bookkeeping. See [`AutoExposureGpu`].
    pub(super) auto_exposure: AutoExposureGpu,
    pub(super) hot_reload: HotReloadState,
    // The world default Shader's compiled programs, `None` for the engine's
    // own. Kept past init for the skinned pipeline built at upload and for the
    // hot-reload rebuild.
    pub(super) world_shader: Option<concinnity_core::components::ShaderPrograms>,
    // Keep each presented drawable's texture retained so `screenshot` can
    // blit it back (the view is blit-readable under the same flag). On under
    // the dev loop and `cn run --screenshot`; false in plain production.
    pub(super) capture: bool,
    // Per-record validity of the GPU-filled model-history ring. A record whose
    // occupant changed carries `NO_HISTORY` in its draw args, which sends the
    // G-buffer pre-pass to its current model instead of a stranger's.
    pub(super) model_history: concinnity_core::render::model_history::ModelHistory,
    // Skinned-mesh rendering feature state: the main + shadow pipelines, the
    // shared skinned vertex / index buffers, the per-mesh draw objects, and
    // the current + previous joint-palette matrices. See [`SkinnedState`].
    pub(super) skinned: SkinnedState,
    pub(super) geometry_alloc: GeometryAllocators,
    pub(super) window: WindowState,
    pub(super) diagnostics: Diagnostics,
    // Frames-in-flight pacing. `draw_frame` acquires a slot before encoding
    // and the frame command buffer's completion handler releases it once the
    // GPU retires the frame, bounding how far the CPU may queue ahead of the
    // GPU (and thus how many sets of per-frame transient buffers can pile up).
    pub(super) frame_pacing: super::frame_pacing::FrameInFlight,
    // Ring depth for the per-frame transient buffers below: equal to the
    // frames-in-flight count (≥1). The fence guarantees frame `R − depth` has
    // retired before frame `R` reuses ring slot `R % depth`, so overwriting
    // that slot's buffer never races an in-flight GPU read.
    pub(super) frames_in_flight: usize,
    // Monotonic counter over frames that build per-frame buffers; `% depth`
    // selects this frame's ring slot. Advanced once per such frame.
    pub(super) frame_ring_index: u64,
    pub(super) rings: FrameRings,
    pub(super) water: WaterState,
    // Planar reflection targets, one set per distinct reflector plane (water
    // surfaces + glass panes, grouped by `assign_planar_slots`). `Some` only when
    // the world declared >=1 such reflector; the scene is re-rendered mirrored
    // across each plane into these each frame (RT off) and the reflective shader
    // samples the resolve of its slot. Rebuilt on resize alongside `hdr_targets`.
    pub(super) planar_reflection: Option<super::planar::PlanarReflectionSet>,
    pub(super) glass: GlassState,
    pub(super) raymarch: RaymarchState,
}

// SAFETY: MtlContext is only ever accessed from the main thread (as documented
// on the struct). The Retained<ProtocolObject<...>> Metal handles aren't Send by
// default, but `RenderBackend: Send` requires it so GraphicsSystem can box
// the backend behind a trait object. Mirrors DxContext / VkContext.
unsafe impl Send for MtlContext {}

// Debug-only guard that the caller is on the main thread.
//
// The `unsafe impl Send for MtlContext` above is sound only because the
// context is touched from the main thread alone: AppKit and Metal command
// submission are both main-thread-affine. `draw_frame` proves this with a
// `MainThreadMarker`, but the `RenderBackend` mutation entry points (reached
// through the boxed trait object) did not, so scheduling `GraphicsSystem`
// off the main thread would silently race AppKit/Metal instead of failing.
// This makes that mistake panic loudly in debug builds and compiles to
// nothing in release. `entry` is the offending method name, for the message.
#[inline]
#[track_caller]
pub(super) fn debug_assert_main_thread(entry: &str) {
    debug_assert!(
        objc2::MainThreadMarker::new().is_some(),
        "{entry} must be called from the main thread: MtlContext is main-thread-only \
         (see `unsafe impl Send for MtlContext`); driving GraphicsSystem off the main \
         thread races AppKit/Metal",
    );
}

// The cull-record set one GPU-driven encode covers: `total` command slots, of
// which the folded skinned tail starts at `skinned_base`. Cull dispatches and
// indirect-draw ranges take this instead of reading the live draw list, so an
// encode whose object + draw-args buffers were snapshotted on an earlier frame
// keeps addressing exactly the records those buffers hold. The reflection-probe
// bake is the one such consumer: it builds its buffers once and renders the six
// cube faces one per frame, while runtime spawns keep growing the live list.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct DrawRecordCounts {
    pub total: usize,
    pub skinned_base: usize,
}

impl DrawRecordCounts {
    // Command slots holding the static objects + folded instances, which draw
    // through the static index buffer. `block` is where the record set starts in
    // the target ICB: 0 for the main ICB, the cascade's block for the shadow ICB.
    // `None` when the set has no such records.
    pub(super) fn prefix(&self, block: usize) -> Option<std::ops::Range<usize>> {
        (self.skinned_base > 0).then(|| block..block + self.skinned_base)
    }

    // Command slots holding the folded skinned tail, which draws compute-deformed
    // vertices through the skinned index buffer. `None` when nothing is folded.
    pub(super) fn skinned_tail(&self, block: usize) -> Option<std::ops::Range<usize>> {
        (self.total > self.skinned_base).then(|| block + self.skinned_base..block + self.total)
    }
}

// The `NSRange` an indirect-draw `executeCommandsInBuffer` takes for `r`.
pub(super) fn ns_range(r: std::ops::Range<usize>) -> objc2_foundation::NSRange {
    objc2_foundation::NSRange {
        location: r.start,
        length: r.end - r.start,
    }
}

impl MtlContext {
    // The record set the live draw list covers. Every frame-driven pass takes
    // this; only the reflection-probe bake substitutes its own snapshot.
    pub(super) fn draw_record_counts(&self) -> DrawRecordCounts {
        DrawRecordCounts {
            total: self.cull_count(),
            skinned_base: self.skinned_record_base(),
        }
    }

    // Number of records the GPU-driven cull processes this frame: the static
    // draw objects, every folded instance, then every folded skinned object.
    // Metal has no separate `n_objects` field; `draw.objects.len()` is the
    // static count. Drives the cull dispatch width + `object_count` uniform, the
    // shared ICB capacity, and the indirect-draw `NSRange`. Equals
    // `draw.objects.len()` for static-only worlds, so those paths are untouched.
    pub(super) fn cull_count(&self) -> usize {
        self.draw.objects.len() + self.draw.n_instances + self.draw.n_skinned
    }

    // The prefiltered radiance cube for probe array slot `i`: the baked probe
    // when present, else the sky `env_map` prefilter (a valid fallback for unused
    // slots and for slots past the baked count). The skybox + diffuse always use
    // `env_map` directly, so they keep the sky regardless.
    pub(super) fn probe_cube_or_sky(&self, i: usize) -> &ProtocolObject<dyn MTLTexture> {
        match self.probe.maps.get(i) {
            Some(p) => &p.prefilter,
            None => self.env_map.prefilter.as_ref(),
        }
    }

    // Index in the unified cull list where the folded skinned records begin
    // (static objects + instances precede them). The cull kernel draws records
    // at or past this through the skinned index buffer (the skinned tail),
    // and the main pass binds the deformed vertex buffer for that range. Equals
    // `cull_count()` when no skinned mesh is folded.
    pub(super) fn skinned_record_base(&self) -> usize {
        self.draw.objects.len() + self.draw.n_instances
    }

    // The buffer to bind at the cull kernel's skinned-index slot (buffer 6):
    // the skinned index buffer when a SkinnedMesh has uploaded, else the
    // static index buffer as a harmless placeholder. The kernel only reads it
    // for records at/after `skinned_base`, which equals `cull_count()` (so the
    // skinned branch never fires) whenever the skinned buffer is absent; Metal
    // still requires a referenced buffer to be bound, hence the placeholder.
    pub(super) fn skinned_index_or_placeholder(
        &self,
    ) -> &ProtocolObject<dyn objc2_metal::MTLBuffer> {
        match self.skinned.index_buffer.as_ref() {
            Some(b) => b.as_ref(),
            None => self.index_buffer.as_ref(),
        }
    }

    // Ensure the GPU-driven cull indirect command buffer has a command slot
    // for every one of `count` draw objects, rebuilding it (and re-encoding
    // its argument buffer) when the draw list has outgrown it. A no-op for
    // non-bindless contexts, which have no cull pipeline. New capacity is
    // rounded up to the next power of two so streamed chunks growing
    // `draw.objects` do not rebuild the ICB every frame.
    //
    // The per-object `cull_status_buffer` (always, for the phase-1 kernel's
    // buffer(5) binding) and (under two-pass occlusion) the phase-2 ICB
    // `cull_icb_2` + its argument buffer are grown in lockstep on the same
    // trigger, so all three stay sized to the live draw-object count.
    pub(super) fn ensure_icb_capacity(&mut self, count: usize) -> Result<(), String> {
        // Retained is reference-counted; cloning the handle lets the rest of
        // the method mutate `self` without holding a borrow on the encoder.
        let arg_encoder = match &self.cull.icb_arg_encoder {
            Some(e) => e.clone(),
            None => return Ok(()),
        };
        if !self.cull.icbs.is_empty() && count <= self.cull.icb_capacity {
            return Ok(());
        }
        let new_cap = count.next_power_of_two().max(64);
        let bucket_count = self.cull.bucket_count.max(1);

        let mut icbs = Vec::with_capacity(bucket_count);
        for _ in 0..bucket_count {
            icbs.push(self.build_cull_icb(new_cap)?);
        }

        // The argument buffer is a fixed-size handle to the ICB array; create
        // it once, then re-encode it to point at each freshly built set.
        if self.cull.icb_arg_buffer.is_none() {
            let len = arg_encoder.encodedLength().max(16);
            let buf = self
                .device
                .newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
                .ok_or("failed to create ICB argument buffer")?;
            self.cull.icb_arg_buffer = Some(buf);
        }
        let arg_buf = self
            .cull
            .icb_arg_buffer
            .as_ref()
            .expect("ICB argument buffer was just ensured");
        // SAFETY: the argument buffer was sized to `encodedLength()`, and each
        // bucket's ICB is encoded at its bucket index within the `icbs`
        // `[[id(0)]]` array of the kernel's `ICBContainer` struct. Entries
        // past `bucket_count` stay null; the kernel never touches them.
        unsafe {
            arg_encoder.setArgumentBuffer_offset(Some(arg_buf), 0);
            for (b, icb) in icbs.iter().enumerate() {
                arg_encoder.setIndirectCommandBuffer_atIndex(Some(icb), b);
            }
        }

        // Per-object status buffer: one u32 per command slot, private storage
        // (GPU-written by phase-1 cull, GPU-read by phase-2 cull). Always
        // allocated so the phase-1 kernel's buffer(5) binding always resolves.
        let status = self
            .device
            .newBufferWithLength_options(
                new_cap * std::mem::size_of::<u32>(),
                MTLResourceOptions::StorageModePrivate,
            )
            .ok_or("failed to create cull status buffer")?;
        self.cull.status_buffer = Some(status);

        // Second-pass ICB + argument buffer, only when two-pass occlusion is on.
        if self.cull.two_pass_occlusion {
            let mut icbs_2 = Vec::with_capacity(bucket_count);
            for _ in 0..bucket_count {
                icbs_2.push(self.build_cull_icb(new_cap)?);
            }
            if self.cull.icb_2_arg_buffer.is_none() {
                let len = arg_encoder.encodedLength().max(16);
                let buf = self
                    .device
                    .newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
                    .ok_or("failed to create phase-2 ICB argument buffer")?;
                self.cull.icb_2_arg_buffer = Some(buf);
            }
            let arg_buf2 = self
                .cull
                .icb_2_arg_buffer
                .as_ref()
                .expect("phase-2 ICB argument buffer was just ensured");
            // SAFETY: same layout as the phase-1 set: each bucket's ICB at its
            // index within the `icbs` `[[id(0)]]` array, and the argument
            // buffer was sized to `encodedLength()`.
            unsafe {
                arg_encoder.setArgumentBuffer_offset(Some(arg_buf2), 0);
                for (b, icb) in icbs_2.iter().enumerate() {
                    arg_encoder.setIndirectCommandBuffer_atIndex(Some(icb), b);
                }
            }
            self.cull.icbs_2 = icbs_2;
        }

        self.cull.icbs = icbs;
        self.cull.icb_capacity = new_cap;
        Ok(())
    }

    // Ensure the GPU-driven cascaded-shadow ICB and its status buffer have a
    // slot for every cascade of every record: `NUM_SHADOW_CASCADES * count`
    // total (cascade `c`'s live at `[c*count, (c+1)*count)`, the same stride
    // `encode_shadow_culls` writes at and the shadow render pass executes). A
    // no-op for non-bindless / no-shadow contexts (no shadow decision pipeline).
    // Rounded to the next power of two so a streamed chunk growing `cull_count()`
    // does not rebuild the ICB every frame. Called from `draw_frame` (where
    // `&mut self` is available) right after `ensure_icb_capacity`, so the encode
    // pass only ever reads the sized ICB.
    pub(super) fn ensure_shadow_icb_capacity(&mut self, count: usize) -> Result<(), String> {
        let arg_encoder = match (&self.cull.shadow_pipeline, &self.cull.icb_arg_encoder) {
            (Some(_), Some(e)) => e.clone(),
            _ => return Ok(()),
        };
        let needed = count.saturating_mul(NUM_SHADOW_CASCADES);
        if self.cull.shadow_icb.is_some() && needed <= self.cull.shadow_icb_capacity {
            return Ok(());
        }
        let new_cap = needed.next_power_of_two().max(64);
        let icb = self.build_cull_icb(new_cap)?;
        if self.cull.shadow_icb_arg_buffer.is_none() {
            let len = arg_encoder.encodedLength().max(16);
            let buf = self
                .device
                .newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
                .ok_or("failed to create shadow ICB argument buffer")?;
            self.cull.shadow_icb_arg_buffer = Some(buf);
        }
        let arg_buf = self
            .cull
            .shadow_icb_arg_buffer
            .as_ref()
            .expect("shadow ICB argument buffer was just ensured");
        // SAFETY: the argument buffer was sized to `encodedLength()`, and the ICB
        // is encoded at slot 0 (the single `[[id(0)]]` member of the kernel's
        // `ICBContainer` argument-buffer struct), exactly like the main ICB.
        unsafe {
            arg_encoder.setArgumentBuffer_offset(Some(arg_buf), 0);
            arg_encoder.setIndirectCommandBuffer_atIndex(Some(&icb), 0);
        }
        // One status word per command slot: each cascade's decision dispatch
        // writes its region, the encode dispatch reads them all back.
        let status = self
            .device
            .newBufferWithLength_options(
                new_cap * std::mem::size_of::<u32>(),
                MTLResourceOptions::StorageModePrivate,
            )
            .ok_or("failed to create shadow cull status buffer")?;
        self.cull.shadow_status = Some(status);
        self.cull.shadow_icb = Some(icb);
        self.cull.shadow_icb_capacity = new_cap;
        Ok(())
    }

    // Ensure `slot_count` per-planar-slot mirror cull ICBs exist, each with a
    // command slot for every one of `count` draw objects (static + folded
    // instances + skinned, exactly like the main ICB). The slots' ICBs + argument
    // buffers are rebuilt when the slot count changes or the draw list outgrows
    // the capacity; the shared single-pass status scratch grows in lockstep. A
    // no-op for non-bindless contexts (no main ICB argument encoder to reuse) and
    // when `slot_count` is 0 (no planar set -> the slots are cleared). Called from
    // `draw_frame` right after `ensure_icb_capacity`, so the planar pass only ever
    // reads a sized mirror ICB.
    pub(super) fn ensure_mirror_icb_capacity(
        &mut self,
        slot_count: usize,
        count: usize,
    ) -> Result<(), String> {
        if slot_count == 0 {
            self.cull.mirror_slots.clear();
            self.cull.mirror_status = None;
            self.cull.mirror_icb_capacity = 0;
            return Ok(());
        }
        // Reuse the main phase-1 ICB argument encoder: a mirror ICB has the
        // identical `ICBContainer` layout (one `[[id(0)]]` member). Absent on
        // non-bindless contexts, where there is no GPU cull to mirror.
        let arg_encoder = match &self.cull.icb_arg_encoder {
            Some(e) => e.clone(),
            None => return Ok(()),
        };
        if self.cull.mirror_slots.len() == slot_count && count <= self.cull.mirror_icb_capacity {
            return Ok(());
        }
        let new_cap = count.next_power_of_two().max(64);
        let mut slots = Vec::with_capacity(slot_count);
        for _ in 0..slot_count {
            let icb = self.build_cull_icb(new_cap)?;
            let len = arg_encoder.encodedLength().max(16);
            let arg_buffer = self
                .device
                .newBufferWithLength_options(len, MTLResourceOptions::StorageModeShared)
                .ok_or("failed to create mirror ICB argument buffer")?;
            // SAFETY: the argument buffer is sized to `encodedLength()` and the
            // ICB is encoded at slot 0, exactly like the main + shadow ICBs. Each
            // slot re-points the shared encoder at its own (arg buffer, ICB) pair;
            // the encoding is fully written before the next slot re-points it.
            unsafe {
                arg_encoder.setArgumentBuffer_offset(Some(&arg_buffer), 0);
                arg_encoder.setIndirectCommandBuffer_atIndex(Some(&icb), 0);
            }
            slots.push(super::cull::MirrorCullSlot { icb, arg_buffer });
        }
        // Shared single-pass status scratch: the mirror cull writes per-object
        // status the same as phase 1, but nothing reads it (no phase-2 over the
        // mirror), so one buffer serves every slot. One u32 per command slot.
        let status = self
            .device
            .newBufferWithLength_options(
                new_cap * std::mem::size_of::<u32>(),
                MTLResourceOptions::StorageModePrivate,
            )
            .ok_or("failed to create mirror cull status buffer")?;
        self.cull.mirror_status = Some(status);
        self.cull.mirror_slots = slots;
        self.cull.mirror_icb_capacity = new_cap;
        Ok(())
    }

    // Create one `DrawIndexed` indirect command buffer with `cap` command
    // slots. Both the phase-1 (`cull_icb`) and phase-2 (`cull_icb_2`) ICBs
    // share this shape: each command inherits the render encoder's buffer
    // bindings + pipeline state, so the cull kernels only encode the
    // indexed-draw arguments. Private storage keeps it GPU-resident
    // (kernel-written, render-pass-consumed, never CPU-touched).
    fn build_cull_icb(
        &self,
        cap: usize,
    ) -> Result<Retained<ProtocolObject<dyn MTLIndirectCommandBuffer>>, String> {
        let desc = MTLIndirectCommandBufferDescriptor::new();
        desc.setCommandTypes(MTLIndirectCommandType::DrawIndexed);
        desc.setInheritBuffers(true);
        desc.setInheritPipelineState(true);
        desc.setMaxVertexBufferBindCount(0);
        desc.setMaxFragmentBufferBindCount(0);
        // SAFETY: `cap` is a valid command count; private storage as documented.
        unsafe {
            self.device
                .newIndirectCommandBufferWithDescriptor_maxCommandCount_options(
                    &desc,
                    cap,
                    MTLResourceOptions::StorageModePrivate,
                )
        }
        .ok_or_else(|| "failed to create indirect command buffer".to_string())
    }

    // Device capability flags for the settings menu. Ray tracing is queried
    // from the live MTLDevice (cheap; the same check the RT pass gates on).
    pub(crate) fn capabilities(&self) -> crate::gfx::backend::DeviceCapabilities {
        crate::gfx::backend::DeviceCapabilities {
            ray_tracing: super::raytrace::raytracing_supported(&self.device),
            // Upscaling always goes through MetalFX; there is no selector.
            selectable_upscaler: false,
            // The per-frame RT topology refresh re-admits recycled build-time
            // slots, so every retired slot may be reused.
            reuses_build_slots: true,
            // The per-object buffer is rebuilt from `draw.objects` every frame,
            // so a slot's rewritten material draws on the next one.
            rewrites_draws: true,
        }
    }

    // Coarse GPU performance profile for default-quality selection, read live
    // from the MTLDevice (cheap; the same kind of device query as capabilities).
    pub(crate) fn gpu_profile(&self) -> crate::gfx::backend::GpuProfile {
        super::gpu_profile::device_profile(&self.device)
    }

    // Render statistics for the most recent `draw_frame`, for the profiler
    // overlay. The GPU frame time is the last value reported by a completed
    // command buffer, so it may lag the draw counts by a frame or two.
    pub(crate) fn render_stats(&self) -> crate::gfx::profile::RenderStats {
        let mut stats = self.diagnostics.frame_stats;
        stats.gpu_frame_us = self
            .diagnostics
            .gpu_time_us
            .load(std::sync::atomic::Ordering::Relaxed);
        // Per-pass timings are filled in pass-index order with their stable
        // names, leaving slots past PASS_COUNT at the default ("", 0).
        // Reports zero for any pass that did not write its sample slot this
        // frame (e.g. SSR when disabled, or any pass not yet wired up).
        for (i, name) in super::pass_timing::PASS_NAMES.iter().enumerate() {
            let micros =
                self.diagnostics.pass_times_us[i].load(std::sync::atomic::Ordering::Relaxed);
            stats.pass_times_us[i] = (*name, micros);
        }
        // Surface the auto-exposure EMA state. `None` when the world did not
        // opt in to auto-exposure (the static-exposure path leaves the field
        // empty so the StatHud chip stays blank).
        stats.auto_exposure_ev = self.auto_exposure.state.as_ref().map(|s| s.current_ev);
        // Surface the active panel's EDR headroom. `None` on SDR: both the
        // world-opt-out case and the request-on-an-SDR-display fallback case
        // map to the same blank chip.
        stats.max_edr = self.hdr.max_edr;
        stats
    }

    // Push a new view matrix; takes effect on the next draw_frame call.
    pub(crate) fn update_view(&mut self, matrix: [[f32; 4]; 4]) {
        self.view.matrix = matrix;
    }

    // Update the model matrices of the given draw objects, one
    // `(slot, matrix)` entry per changed object. Out-of-range slots have no
    // effect.
    pub(crate) fn update_models(&mut self, updates: &[(u32, [[f32; 4]; 4])]) {
        for &(index, model) in updates {
            if let Some(obj) = self.draw.objects.get_mut(index as usize) {
                obj.model = model;
            }
        }
    }

    // Show or hide a single draw object. Hidden objects are skipped in both
    // the shadow and main passes. Has no effect if the index is out of range.
    pub(crate) fn update_visibility(&mut self, index: usize, visible: bool) {
        if let Some(obj) = self.draw.objects.get_mut(index) {
            obj.visible = visible;
        }
    }

    // Retire a draw object for a despawned entity: clear `visible` (drops it
    // from the main / shadow / velocity passes) and `resident` (drops it from
    // the ray-tracing BLAS / geometry-table rebuild), so it leaves no ghost in
    // any pass. The geometry buffers stay allocated; the engine's draw-slot
    // allocator recycles the index. Has no effect if the index is out of range.
    pub(crate) fn retire_draw_object(&mut self, index: usize) {
        if let Some(obj) = self.draw.objects.get_mut(index) {
            obj.visible = false;
            obj.resident = false;
        }
    }

    // Write a draw object at the destination slot the engine's allocator
    // chose: overwrite a reused slot in place, or append a new one (the
    // engine's allocator mirrors this vec's length, so an Append index always
    // equals it).
    pub(super) fn place_draw_object(
        &mut self,
        obj: DrawObject,
        dst: crate::gfx::draw_slot::SlotAlloc,
    ) -> usize {
        match dst {
            crate::gfx::draw_slot::SlotAlloc::Reuse(slot) => {
                self.draw.objects[slot] = obj;
                self.model_history.reoccupy_draw(slot);
                slot
            }
            crate::gfx::draw_slot::SlotAlloc::Append(slot) => {
                debug_assert_eq!(
                    slot,
                    self.draw.objects.len(),
                    "appended draw slot must match the draw-object count"
                );
                self.draw.objects.push(obj);
                self.model_history.reoccupy_draw(slot);
                slot
            }
        }
    }

    // Set the scene-transition fade for the next draw_frame call. Applied in
    // the composite pass, so a FadeBlack fades the whole image.
    pub(crate) fn set_fade(&mut self, fade: f32) {
        self.view.scene_fade = fade.clamp(0.0, 1.0);
    }

    // Instantiate a runtime copy of an existing draw object at a new transform:
    // re-use the source slot's geometry region (vertex/index offsets,
    // base_vertex, LOD alternates) and copy its texture slots, material, and
    // cull distance, swapping only the model matrix. Driven by runtime entity
    // spawn (`SpawnRequest`); the destination slot comes from the engine's
    // allocator. The copy is marked non-cullable (sentinel AABB), so the GPU
    // cull admits it every frame like a streamed chunk.
    pub(crate) fn clone_static_draw_object(
        &mut self,
        src_draw_idx: usize,
        model: [[f32; 4]; 4],
        dst: crate::gfx::draw_slot::SlotAlloc,
    ) -> Result<(), String> {
        let src = self.draw.objects.get(src_draw_idx).ok_or_else(|| {
            format!(
                "clone_static_draw_object: src draw {} out of range",
                src_draw_idx
            )
        })?;
        let obj = DrawObject {
            vertex_offset: src.vertex_offset,
            vertex_count: src.vertex_count,
            index_offset: src.index_offset,
            index_count: src.index_count,
            base_vertex: src.base_vertex,
            geometry_generation: src.geometry_generation,
            model,
            texture_slot: src.texture_slot,
            normal_map_slot: src.normal_map_slot,
            material: src.material,
            shader_bucket: src.shader_bucket,
            visible: true,
            resident: true,
            bb_min: [f32::NAN; 3],
            bb_max: [f32::NAN; 3],
            cull_distance: src.cull_distance,
            lod_alternates: src.lod_alternates.clone(),
        };
        self.place_draw_object(obj, dst);
        // The cloned prop joins the RT-relevant draw set; the next RT update
        // folds it into the BVH (it reuses the source mesh's geometry slice, so
        // only this clone's BLAS is built).
        self.rt.topology_dirty = true;
        Ok(())
    }

    // Rewrite a draw slot's material parameters + texture/normal-map pool
    // indices in place. Driven by the editor's live draw seam when a Prop edits
    // its `material` arg. Has no effect if the index is out of range.
    pub(crate) fn set_draw_material(
        &mut self,
        draw_idx: usize,
        material: crate::gfx::render_types::MaterialUniforms,
        texture_slot: usize,
        normal_map_slot: usize,
    ) {
        if let Some(obj) = self.draw.objects.get_mut(draw_idx) {
            obj.material = material;
            obj.texture_slot = texture_slot;
            obj.normal_map_slot = normal_map_slot;
            // A material edit can flip RT participation (`see_through`) and always
            // changes the geometry-table entry; flag a topology refresh so the
            // next RT update rebuilds the table (BLAS are reused -- geometry is
            // unchanged -- so this is cheap).
            self.rt.topology_dirty = true;
        }
    }

    // Rewrite a draw slot's `cull_distance` in place. Driven by the editor's
    // live draw seam when a Prop edits its `cull_distance` arg. Has no effect
    // if the index is out of range.
    pub(crate) fn set_draw_cull_distance(&mut self, draw_idx: usize, cull_distance: f32) {
        if let Some(obj) = self.draw.objects.get_mut(draw_idx) {
            obj.cull_distance = cull_distance.max(0.0);
        }
    }

    // Append a projected-decal record at runtime, returning a stable slot
    // index the caller hands to [`Self::remove_decal`] later. Builds the
    // decal pipeline + unit-cube buffers on first use so a world that never
    // declared a decal still pays zero pipeline cost until the first add.
    // A vacated slot from [`Self::remove_decal`] is reused before growing
    // the slot table so a steady-state spawn/despawn pattern (bullet holes,
    // footprints) stays bounded.
    pub(crate) fn add_decal(
        &mut self,
        record: crate::gfx::decal::DecalRecord,
    ) -> Result<usize, String> {
        if self.decal.pipeline.is_none() {
            let (ps, vbuf, ibuf, samp) = super::init::effects::build_decal_resources_for_runtime(
                &self.device,
                self.hot_reload.enabled,
            )?;
            self.decal.pipeline = Some(ps);
            self.decal.cube_vertex_buffer = Some(vbuf);
            self.decal.cube_index_buffer = Some(ibuf);
            self.decal.sampler = Some(samp);
        }
        self.decal
            .set
            .insert(record)
            .map_err(|_| "add_decal: decal set is full".to_string())
    }

    // Tombstone a runtime decal slot. The slot index returned by
    // [`Self::add_decal`] becomes invalid; the next add may reuse it.
    // Returns an error when the index is out of range or already tombstoned.
    // The decal pipeline + unit-cube buffers are kept around so a later add
    // does not pay the rebuild cost.
    pub(crate) fn remove_decal(&mut self, decal_id: usize) -> Result<(), String> {
        self.decal
            .set
            .remove(decal_id)
            .map_err(|e| format!("remove_decal: id {decal_id} {e}"))
    }

    // Append a particle-emitter record at runtime, returning a stable slot
    // index. Allocates the per-emitter GPU pool + atomic counter buffer
    // (matching the init-time path) and builds the compute + render
    // pipelines on first use so a world that never declared an emitter
    // pays zero pipeline cost until the first add. Tombstoned slots from
    // [`Self::remove_emitter`] are reused before growing the vec.
    pub(crate) fn add_emitter(
        &mut self,
        record: crate::gfx::particles::ParticleEmitterRecord,
    ) -> Result<usize, String> {
        if self.particle.pipelines.is_none() {
            let pipelines =
                super::particle::build_particle_pipelines(&self.device, self.hot_reload.enabled)?;
            self.particle.pipelines = Some(pipelines);
        }
        let gpu_state =
            super::particle::build_emitter_gpu_state(&self.device, &record, self.frames_in_flight)?;
        let idx = if let Some(slot) = self.particle.free_slots.pop() {
            self.particle.records[slot] = Some(record);
            self.particle.emitter_state[slot] = Some(gpu_state);
            slot
        } else {
            self.particle.records.push(Some(record));
            self.particle.emitter_state.push(Some(gpu_state));
            self.particle.records.len() - 1
        };
        Ok(idx)
    }

    // Tombstone a runtime emitter slot. Drops the `ParticleEmitterGpuState`:
    // Metal keeps the underlying pool + counter buffers alive until any
    // in-flight command buffer referencing them completes, so this is safe
    // to call mid-frame between encode passes (the debug-WS path runs in
    // the `DebugHook::tick` window before the world step). Returns an error
    // when the index is out of range or already tombstoned.
    pub(crate) fn remove_emitter(&mut self, emitter_id: usize) -> Result<(), String> {
        let rec_slot = self
            .particle
            .records
            .get_mut(emitter_id)
            .ok_or_else(|| format!("remove_emitter: id {} out of range", emitter_id))?;
        if rec_slot.is_none() {
            return Err(format!("remove_emitter: id {} already removed", emitter_id));
        }
        *rec_slot = None;
        if let Some(gpu_slot) = self.particle.emitter_state.get_mut(emitter_id) {
            *gpu_slot = None;
        }
        self.particle.free_slots.push(emitter_id);
        Ok(())
    }

    // Returns true if the window has been closed by the user.
    pub(crate) fn window_closed(&self) -> bool {
        if self.window.appkit.closed() {
            return true;
        }
        // Detect close via the red-X button: NSWindow.close() hides the window
        // without posting an ApplicationDefined event, so window_closed never
        // becomes true through the event pump alone. Guard with was_visible so
        // we don't misfire before the first frame appears.
        self.window.was_visible && self.window.appkit.window().is_some_and(|w| !w.isVisible())
    }

    // Block until the GPU has finished all in-flight work.
    pub(crate) fn wait_idle(&self) {
        if let Some(cmd_buf) = self.command_queue.commandBuffer() {
            cmd_buf.commit();
            cmd_buf.waitUntilCompleted();
        }
    }

    // Drain the classified GPU failure a completion handler parked, if any.
    pub(super) fn take_device_error(&self) -> Option<crate::gfx::error::RenderError> {
        self.diagnostics
            .device_error
            .lock()
            .ok()
            .and_then(|mut slot| slot.take())
    }
}

impl crate::gfx::scene_flow::SceneControl for MtlContext {
    fn update_visibility(&mut self, draw_idx: usize, visible: bool) {
        self.update_visibility(draw_idx, visible);
    }

    fn set_fade(&mut self, fade: f32) {
        self.set_fade(fade);
    }
}

impl Drop for MtlContext {
    fn drop(&mut self) {
        // Wait for all in-flight GPU work to finish before releasing Metal
        // objects. Without this, releasing the command queue while the GPU is
        // still executing a committed command buffer can corrupt ObjC retain
        // counts and produce EXC_BAD_ACCESS in objc_release.
        self.wait_idle();
        // Write whatever metallibs were compiled lazily since init's own
        // checkpoint. Ahead of the reload guard below: the artifacts belong to
        // the process, not to the window this context may have handed on.
        crate::runtime_cache::checkpoint();
        // A context whose window was transplanted to a successor (a live editor
        // reload) must tear nothing down: the successor owns the window, view,
        // and cursor state now, so closing the window here would order the reused
        // window out from under it.
        if !self.window.owns {
            return;
        }
        // Always release the cursor on teardown so the OS mouse association and
        // cursor visibility are restored even if the caller didn't do it.
        self.window.appkit.release_cursor();
        if let Some(window) = self.window.appkit.window() {
            // Close the game window so it doesn't linger after the run loop exits.
            window.close();
        } else {
            // In embedded mode (no NSWindow), the MTKView was added as a subview.
            // Explicitly remove it so it doesn't outlive the preview session.
            self.window.view.removeFromSuperview();
        }
    }
}

// Reinterpret a POD slice as raw bytes for a GPU buffer copy.
// Copy the first `len` bytes of `src` into `dst`. Both must be
// shared-storage buffers at least `len` bytes long; used by
// `setup_chunk_streaming` to carry build-time geometry into a grown buffer.
pub(super) fn copy_buffer_prefix(
    src: &ProtocolObject<dyn MTLBuffer>,
    dst: &ProtocolObject<dyn MTLBuffer>,
    len: usize,
) {
    if len == 0 {
        return;
    }
    assert!(
        len <= src.length() && len <= dst.length(),
        "copy_buffer_prefix: {len} bytes exceeds src {} / dst {}",
        src.length(),
        dst.length()
    );
    // SAFETY: both buffers are shared storage, so `contents()` is a live CPU
    // mapping, and the assert above proved each holds at least `len` bytes.
    // They are distinct allocations, so the ranges cannot overlap.
    unsafe {
        let s = src.contents().as_ptr() as *const u8;
        let d = dst.contents().as_ptr() as *mut u8;
        std::ptr::copy_nonoverlapping(s, d, len);
    }
}

pub(super) fn bytes_of_slice<T: bytemuck::NoUninit>(slice: &[T]) -> &[u8] {
    bytemuck::cast_slice(slice)
}

// Copy a `#[repr(C)]` slice into a shared-storage buffer at offset 0,
// bounds-checked against the buffer length.
pub(super) fn write_buffer_slice<T: Copy>(
    buffer: &ProtocolObject<dyn MTLBuffer>,
    data: &[T],
) -> Result<(), String> {
    let bytes = std::mem::size_of_val(data);
    if bytes == 0 {
        return Ok(());
    }
    let len = buffer.length();
    if bytes > len {
        return Err(format!(
            "buffer write of {bytes} bytes exceeds buffer length {len}"
        ));
    }
    // SAFETY: `buffer` is shared storage so `contents()` is a live CPU mapping, and the bounds
    // check above proved it holds `bytes`. `data` is a separate live borrow of exactly that
    // many bytes (padding is copied, never inspected), so the ranges cannot overlap.
    unsafe {
        std::ptr::copy_nonoverlapping(
            data.as_ptr().cast::<u8>(),
            buffer.contents().as_ptr().cast::<u8>(),
            bytes,
        );
    }
    Ok(())
}

// Copy `src` into a shared-storage buffer at `offset` bytes, bounds-checked
// against the buffer length.
pub(super) fn write_buffer_region(
    buffer: &ProtocolObject<dyn MTLBuffer>,
    offset: usize,
    src: &[u8],
) -> Result<(), String> {
    let len = buffer.length();
    if offset.checked_add(src.len()).is_none_or(|end| end > len) {
        return Err(format!(
            "buffer write [{}, {}) exceeds buffer length {}",
            offset,
            offset.saturating_add(src.len()),
            len
        ));
    }
    if src.is_empty() {
        return Ok(());
    }
    let dst = buffer.contents().as_ptr() as *mut u8;
    // SAFETY: `buffer` is shared storage so `contents()` is a live CPU mapping, and the bounds
    // check above proved `offset + src.len()` is within its length. `src` is a separate borrow, so
    // the ranges cannot overlap.
    unsafe {
        std::ptr::copy_nonoverlapping(src.as_ptr(), dst.add(offset), src.len());
    }
    Ok(())
}

// Zero a `len`-byte region of a shared-storage buffer at `offset` bytes,
// bounds-checked against the buffer length.
pub(super) fn zero_buffer_region(
    buffer: &ProtocolObject<dyn MTLBuffer>,
    offset: usize,
    len: usize,
) -> Result<(), String> {
    let buf_len = buffer.length();
    if offset.checked_add(len).is_none_or(|end| end > buf_len) {
        return Err(format!(
            "buffer zero [{}, {}) exceeds buffer length {}",
            offset,
            offset.saturating_add(len),
            buf_len
        ));
    }
    if len == 0 {
        return Ok(());
    }
    let dst = buffer.contents().as_ptr() as *mut u8;
    // SAFETY: `buffer` is shared storage so `contents()` is a live CPU mapping, and the bounds
    // check above proved `offset + len` is within its length.
    unsafe {
        std::ptr::write_bytes(dst.add(offset), 0, len);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn counts(total: usize, skinned_base: usize) -> DrawRecordCounts {
        DrawRecordCounts {
            total,
            skinned_base,
        }
    }

    #[test]
    fn static_only_set_is_all_prefix() {
        let c = counts(12, 12);
        assert_eq!(c.prefix(0), Some(0..12));
        assert_eq!(c.skinned_tail(0), None);
    }

    #[test]
    fn folded_skinned_set_splits_at_the_base() {
        let c = counts(12, 9);
        assert_eq!(c.prefix(0), Some(0..9));
        assert_eq!(c.skinned_tail(0), Some(9..12));
    }

    #[test]
    fn skinned_only_set_has_no_prefix() {
        let c = counts(4, 0);
        assert_eq!(c.prefix(0), None);
        assert_eq!(c.skinned_tail(0), Some(0..4));
    }

    #[test]
    fn empty_set_yields_no_ranges() {
        let c = counts(0, 0);
        assert_eq!(c.prefix(0), None);
        assert_eq!(c.skinned_tail(0), None);
    }

    #[test]
    fn block_offsets_both_ranges_into_a_cascade() {
        let c = counts(12, 9);
        assert_eq!(c.prefix(24), Some(24..33));
        assert_eq!(c.skinned_tail(24), Some(33..36));
    }

    #[test]
    fn ranges_stay_inside_the_block_they_start() {
        let c = counts(12, 9);
        for cascade in 0..4 {
            let block = cascade * c.total;
            let tail = c.skinned_tail(block).expect("skinned tail");
            assert_eq!(c.prefix(block).expect("prefix").start, block);
            assert_eq!(tail.end, block + c.total);
        }
    }

    #[test]
    fn ns_range_carries_start_and_length() {
        let r = ns_range(9..12);
        assert_eq!(r.location, 9);
        assert_eq!(r.length, 3);
    }
}