codecraft 0.1.1

A minimalist 3D game engine built on parts of Bevy (ECS, color) with wgpu and winit: OpenPBR materials, clustered lighting, an immediate-mode UI, audio and gamepad haptics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
//! Drawing loaded meshes: a camera, a mesh library, and one instanced draw
//! call per mesh.
use std::collections::HashMap;

use bytemuck::{Pod, Zeroable};

use crate::material::Material;
use crate::sceneobjects::lights::{Ambient, Light, Suns};
use bevy_color::Alpha;
use glam::{Mat4, Vec3};
use wgpu::util::DeviceExt;

use bevy_ecs::schedule::IntoScheduleConfigs;

use crate::ecs::{Application, Plugin, Resource};
use crate::materials::openpbr::{
    EnergyTables, Material as OpenPbrMaterial, OpenPbrSurface, material_of,
};
use crate::mesh::{MeshData, Vertex};
use crate::sceneobjects::lights::GpuLight;
use crate::ui::{Color, linear_rgba, wgpu_color};

/// How many distinct surfaces one scene can register. A board has a handful:
/// the two sides, the two squares, and whatever the frame is made of.
pub const MAX_MATERIALS: usize = 256;

/// A mesh uploaded to the GPU. Cheap to copy; see [`crate::AppState::mesh`].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct MeshId(pub usize);

/// Where the meshes loaded from an asset ended up, by node name.
#[derive(Resource, Clone, Default, Debug)]
pub struct MeshHandles(HashMap<String, MeshId>);

impl MeshHandles {
    pub fn get(&self, name: &str) -> Option<MeshId> {
        self.0.get(name).copied()
    }

    pub fn insert(&mut self, name: impl Into<String>, id: MeshId) {
        self.0.insert(name.into(), id);
    }

    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.0.keys().map(String::as_str)
    }
}

// The camera lives in its own module now; re-exported so `render3d::Camera`
// keeps working for anything that already reached for it there.
pub use crate::sceneobjects::cameras::{Camera, OrbitCamera, Ray};

/// Placement of a model in the world: where it stands, which way it faces,
/// and how big it is.
///
/// The rotation is a full quaternion rather than a heading, because not
/// everything placed in a world stands upright — a piece on a board only ever
/// turns about Y, but something being flown around does all three.
#[derive(crate::ecs::Component, Clone, Copy, Debug)]
pub struct Transform {
    pub translation: Vec3,
    pub rotation: glam::Quat,
    pub scale: f32,
}

impl Default for Transform {
    fn default() -> Self {
        Self {
            translation: Vec3::ZERO,
            rotation: glam::Quat::IDENTITY,
            scale: 1.0,
        }
    }
}

impl Transform {
    pub fn at(x: f32, y: f32, z: f32) -> Self {
        Self {
            translation: Vec3::new(x, y, z),
            ..Self::default()
        }
    }

    /// Facing, as a turn about the up axis in radians — the common case, and
    /// what an asset exported facing +Z is placed with.
    pub fn set_yaw(&mut self, radians: f32) {
        self.rotation = glam::Quat::from_rotation_y(radians);
    }

    /// Turns by `rotation` in world axes, so a yaw stays a yaw however the
    /// model is already leaning. Left-multiplied for that reason.
    pub fn rotate(&mut self, rotation: glam::Quat) {
        self.rotation = (rotation * self.rotation).normalize();
    }

    pub fn matrix(&self) -> Mat4 {
        Mat4::from_scale_rotation_translation(
            Vec3::splat(self.scale),
            self.rotation,
            self.translation,
        )
    }
}

/// A surface registered with the renderer, as [`MeshId`] is a mesh.
///
/// Materials are shared: every white piece on the board is the same polished
/// dielectric, differing only in the tint its instance carries, so the table
/// holds one entry however many pieces are standing on it.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct MaterialId(pub u32);

/// The mesh an entity draws, the color to draw it in, and how it takes light.
#[derive(crate::ecs::Component, Clone, Copy, Debug)]
pub struct MeshInstance {
    pub mesh: MeshId,
    /// Multiplies the material's base colour, which is what lets one material
    /// serve both sides of the board.
    pub color: Color,
    pub material: MaterialId,
}

/// One model as the GPU sees it.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct ModelInstance {
    model: [f32; 16],
    color: [f32; 4],
    /// x: which material in the table. The rest is spare, and a `u32` row
    /// rather than three because the attribute has to be a whole vector.
    material: [u32; 4],
}

impl ModelInstance {
    pub fn model(&self) -> Mat4 {
        Mat4::from_cols_array(&self.model)
    }
}

/// The models to draw this frame, gathered by [`collect_models_system`] and
/// sorted so each mesh is one instanced draw call.
///
/// Solid and see-through are kept apart: a translucent model has to be drawn
/// after everything behind it, and without writing depth, or it hides what it
/// is supposed to show through to.
#[derive(Resource, Default)]
pub struct ModelDrawList {
    pub opaque: Vec<(MeshId, ModelInstance)>,
    pub translucent: Vec<(MeshId, ModelInstance)>,
}

pub fn collect_models_system(
    mut draw_list: bevy_ecs::system::ResMut<ModelDrawList>,
    models: bevy_ecs::system::Query<(&Transform, &MeshInstance)>,
) {
    draw_list.opaque.clear();
    draw_list.translucent.clear();

    for (transform, instance) in &models {
        let draw = (
            instance.mesh,
            ModelInstance {
                model: transform.matrix().to_cols_array(),
                color: linear_rgba(instance.color),
                material: [instance.material.0, 0, 0, 0],
            },
        );
        if instance.color.alpha() < 1.0 {
            draw_list.translucent.push(draw);
        } else {
            draw_list.opaque.push(draw);
        }
    }

    // Batching below walks runs of equal mesh ids.
    draw_list.opaque.sort_by_key(|(mesh, _)| *mesh);
    draw_list.translucent.sort_by_key(|(mesh, _)| *mesh);
}

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct CameraUniform {
    view_proj: [f32; 16],
    light_view_proj: [f32; 16],
    /// Straight down over the scene, for the occlusion map.
    ao_view_proj: [f32; 16],
    /// xyz towards the key light, w its strength.
    light_dir: [f32; 4],
    key_color: [f32; 4],
    /// xyz towards the rim light, w its strength.
    rim_dir: [f32; 4],
    rim_color: [f32; 4],
    ambient: [f32; 4],
    /// Where the camera is, for the half-angle a highlight needs.
    eye: [f32; 4],
    /// x: penumbra per unit of map depth, y: a shadow texel in world units,
    /// z: a shadow texel in uv.
    shadow: [f32; 4],
    /// x: how far the occlusion hunt reaches in the map's uv, y: world height
    /// per unit of its depth, z: how much it darkens, w: that reach in world
    /// units.
    ao: [f32; 4],
    /// x: how many local lights there are this frame. A count rather than
    /// `arrayLength`, which would answer with the whole fixed-size buffer.
    counts: [f32; 4],
    /// x, y: scale and bias taking a view-space depth to a cluster slice --
    /// the same pair the culling pass used, so the two agree about which cell
    /// a fragment is in. z, w: the frame in pixels.
    cluster: [f32; 4],
}

/// How the shadow map was fitted around the scene this frame.
#[derive(Clone, Copy, Debug)]
pub struct ShadowFit {
    pub light_view_proj: Mat4,
    /// Penumbra radius per unit of map depth, in the map's uv. By similar
    /// triangles this is `tan(angle) * depth_span / width`; the map's scale
    /// cancels, so nothing downstream has to know how big the scene is.
    pub spread: f32,
    /// One shadow texel, in world units — the scale the depth bias works in.
    pub texel_world: f32,
    /// World units from the near plane to the far one, which is what a unit
    /// of the map's depth is worth.
    pub depth_span: f32,
    /// How wide the fitted box is, in world units.
    pub width: f32,
}

/// Fits an orthographic light view around `min..max`.
///
/// The box is sized to the bounds' bounding sphere so that it does not change
/// as the light swings around, and pulled back far enough that everything
/// casting into the volume is in front of the near plane.
pub fn fit_light(
    min: Vec3,
    max: Vec3,
    light_dir: Vec3,
    angle_degrees: f32,
    map_size: f32,
) -> ShadowFit {
    let center = (min + max) * 0.5;
    let radius = ((max - min).length() * 0.5).max(1e-5);
    let direction = light_dir.normalize_or(Vec3::Y);
    // look_at needs an up that is not the direction itself.
    let up = if direction.y.abs() > 0.99 {
        Vec3::Z
    } else {
        Vec3::Y
    };

    let eye = center + direction * radius * 2.0;
    let view = glam::camera::rh::view::look_at_mat4(eye, center, up);
    let (near, far) = (0.0, radius * 4.0);
    let projection =
        glam::camera::rh::proj::directx::orthographic(-radius, radius, -radius, radius, near, far);

    let width = radius * 2.0;
    ShadowFit {
        light_view_proj: projection * view,
        spread: angle_degrees.to_radians().tan() * (far - near) / width,
        texel_world: width / map_size.max(1.0),
        depth_span: far - near,
        width,
    }
}

/// The world-space bounds of everything being drawn, for [`fit_light`].
///
/// Returns `None` when there is nothing to draw, in which case there is
/// nothing to fit a shadow map around either.
pub fn scene_bounds(
    draws: &[(MeshId, ModelInstance)],
    bounds_of: impl Fn(MeshId) -> Option<(Vec3, Vec3)>,
) -> Option<(Vec3, Vec3)> {
    let mut min = Vec3::splat(f32::MAX);
    let mut max = Vec3::splat(f32::MIN);
    let mut any = false;

    for (mesh, instance) in draws {
        let Some((local_min, local_max)) = bounds_of(*mesh) else {
            continue;
        };
        let model = Mat4::from_cols_array(&instance.model);
        // Every corner, because a rotated box's extent is not its extent.
        for i in 0..8 {
            let corner = Vec3::new(
                if i & 1 == 0 { local_min.x } else { local_max.x },
                if i & 2 == 0 { local_min.y } else { local_max.y },
                if i & 4 == 0 { local_min.z } else { local_max.z },
            );
            let world = model.transform_point3(corner);
            min = min.min(world);
            max = max.max(world);
            any = true;
        }
    }

    any.then_some((min, max))
}

struct GpuMesh {
    vertices: wgpu::Buffer,
    indices: wgpu::Buffer,
    index_count: u32,
    /// The material color from the asset, used when an instance doesn't
    /// override it.
    base_color: Option<Color>,
    /// Local-space bounds, for fitting the shadow map.
    min: Vec3,
    max: Vec3,
}

/// Shared with anything else drawing into the same frame — see
/// [`crate::gizmos::GridRenderer`], which tests against this pass's depth.
pub const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;

/// Resolution of the shadow map. One light, one map, so it can afford to be
/// generous: a penumbra is only as fine as the texels it is filtered over.
const SHADOW_MAP_SIZE: u32 = 2048;

/// Resolution of the occlusion map — a height field looked at from straight
/// above, read blurrily, so it does not need the shadow map's fineness.
const AO_MAP_SIZE: u32 = 1024;

/// How far the occlusion hunt reaches, as a fraction of the fitted box. About
/// a piece and a half across the board, which is the distance over which one
/// piece shades the board beside it.
const AO_REACH: f32 = 0.045;

/// Samples per pixel. Four is the usual bargain: most of the stair-stepping
/// gone, and no pass of its own to pay for.
pub const SAMPLES: u32 = 4;

/// The images a frame is drawn into, handed out by
/// [`MeshRenderer::targets`] so that every 3D pass draws into the same ones.
pub struct Targets<'a> {
    /// Multisampled, and where the drawing actually happens.
    pub color: &'a wgpu::TextureView,
    /// What `color` is resolved down to at the end of each pass.
    pub resolve: &'a wgpu::TextureView,
    /// Shared depth, so a later pass is occluded by an earlier one.
    pub depth: &'a wgpu::TextureView,
}

/// A read-only storage buffer the fragment stage reads. Three of the model's
/// bindings are the same shape, and saying so once is clearer than saying it
/// three times.
fn storage_entry(binding: u32) -> wgpu::BindGroupLayoutEntry {
    wgpu::BindGroupLayoutEntry {
        binding,
        visibility: wgpu::ShaderStages::FRAGMENT,
        ty: wgpu::BindingType::Buffer {
            ty: wgpu::BufferBindingType::Storage { read_only: true },
            has_dynamic_offset: false,
            min_binding_size: None,
        },
        count: None,
    }
}

/// Draws [`ModelDrawList`] with one instanced draw call per mesh.
pub struct MeshRenderer {
    pipeline: wgpu::RenderPipeline,
    translucent_pipeline: wgpu::RenderPipeline,
    shadow_pipeline: wgpu::RenderPipeline,
    camera_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
    shadow_bind_group: wgpu::BindGroup,
    shadow_view: wgpu::TextureView,
    ao_pipeline: wgpu::RenderPipeline,
    ao_view: wgpu::TextureView,
    /// The multisampled image the scene is drawn into before being resolved
    /// down to the one the tonemapper reads, with the size it was made for.
    msaa: Option<(u32, u32, wgpu::TextureView)>,
    /// What `msaa` resolves down to: the finished HDR frame, still linear
    /// light, waiting for [`crate::tonemap`] to make a picture of it.
    resolve: Option<(u32, u32, wgpu::TextureView)>,
    /// The format of the image being drawn into, which the multisampled one
    /// has to match.
    format: wgpu::TextureFormat,
    instance_buffer: wgpu::Buffer,
    instance_capacity: usize,
    meshes: Vec<GpuMesh>,
    depth: Option<(u32, u32, wgpu::TextureView)>,
    /// Every surface a scene has registered, packed as the shader reads them,
    /// with the energy tables for each in the same order.
    materials: Vec<OpenPbrMaterial>,
    energy: Vec<f32>,
    /// How many of `materials` have reached the GPU. The table only grows, so
    /// a count is enough to know what is left to send.
    materials_uploaded: usize,
    material_buffer: wgpu::Buffer,
    energy_buffer: wgpu::Buffer,
}

impl MeshRenderer {
    pub fn new(
        device: &wgpu::Device,
        format: wgpu::TextureFormat,
        clusters: &crate::clustered::Clusters,
    ) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("model shader"),
            // The library, then the pass that drives it. Built here rather
            // than `concat!`ed because the library is one `const` already and
            // repeating its file list is how the two come to disagree.
            source: wgpu::ShaderSource::Wgsl(
                format!(
                    "{}\n{}",
                    crate::materials::openpbr::SHADER,
                    include_str!("model.wgsl"),
                )
                .into(),
            ),
        });

        let camera_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("model camera uniform"),
            size: std::mem::size_of::<CameraUniform>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let shadow_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("shadow map"),
            size: wgpu::Extent3d {
                width: SHADOW_MAP_SIZE,
                height: SHADOW_MAP_SIZE,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: DEPTH_FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let shadow_view = shadow_texture.create_view(&wgpu::TextureViewDescriptor::default());

        let ao_texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("occlusion map"),
            size: wgpu::Extent3d {
                width: AO_MAP_SIZE,
                height: AO_MAP_SIZE,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: DEPTH_FORMAT,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let ao_view = ao_texture.create_view(&wgpu::TextureViewDescriptor::default());

        // A comparison sampler: each tap tests and blends four texels on the
        // way back, so a filter tap returns a fraction rather than a yes or no.
        let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("shadow sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            compare: Some(wgpu::CompareFunction::LessEqual),
            ..Default::default()
        });

        // Fixed sizes, made once. The table only ever grows within them, so
        // the bind group is built here and never rebuilt -- a buffer that is
        // replaced when a scene registers its ninth material is a bind group
        // that has to be rebuilt in the middle of a frame.
        let material_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("openpbr materials"),
            size: (MAX_MATERIALS * std::mem::size_of::<OpenPbrMaterial>()) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let energy_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("openpbr energy tables"),
            size: (MAX_MATERIALS * std::mem::size_of::<EnergyTables>()) as u64,
            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("model bind group layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Depth,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Comparison),
                    count: None,
                },
                // The occlusion map is read as heights, never compared, so it
                // needs no sampler of its own.
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Depth,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                // The material table, the energy tables that go with it, and
                // the lights: read-only storage, all three, and all three read
                // only where the shading happens.
                storage_entry(4),
                storage_entry(5),
                // The lights, and the grid that says which of them reach
                // here: filled by the culling pass before this one runs.
                storage_entry(6),
                storage_entry(7),
                storage_entry(8),
            ],
        });

        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("model bind group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: camera_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&shadow_view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&shadow_sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::TextureView(&ao_view),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: material_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 5,
                    resource: energy_buffer.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 6,
                    resource: clusters.lights.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 7,
                    resource: clusters.counts.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 8,
                    resource: clusters.indices.as_entire_binding(),
                },
            ],
        });

        // The shadow pass writes the map, so it cannot also bind it.
        let shadow_bind_group_layout =
            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
                label: Some("shadow bind group layout"),
                entries: &[wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                }],
            });
        let shadow_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("shadow bind group"),
            layout: &shadow_bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: camera_buffer.as_entire_binding(),
            }],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("model pipeline layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });

        const VERTEX_ATTRS: [wgpu::VertexAttribute; 2] =
            wgpu::vertex_attr_array![0 => Float32x3, 1 => Float32x3];
        const INSTANCE_ATTRS: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![
            2 => Float32x4, 3 => Float32x4, 4 => Float32x4, 5 => Float32x4, 6 => Float32x4,
            7 => Uint32x4
        ];

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("model pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<Vertex>() as u64,
                        step_mode: wgpu::VertexStepMode::Vertex,
                        attributes: &VERTEX_ATTRS,
                    }),
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<ModelInstance>() as u64,
                        step_mode: wgpu::VertexStepMode::Instance,
                        attributes: &INSTANCE_ATTRS,
                    }),
                ],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::REPLACE),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: SAMPLES,
                ..wgpu::MultisampleState::default()
            },
            multiview_mask: None,
            cache: None,
        });

        let shadow_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("shadow shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shadow.wgsl").into()),
        });
        let shadow_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("shadow pipeline layout"),
            bind_group_layouts: &[Some(&shadow_bind_group_layout)],
            immediate_size: 0,
        });
        // Position and the instance transform only — depth is the product, so
        // normals and colors are not read.
        const SHADOW_VERTEX_ATTRS: [wgpu::VertexAttribute; 1] =
            wgpu::vertex_attr_array![0 => Float32x3];
        let shadow_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("shadow pipeline"),
            layout: Some(&shadow_layout),
            vertex: wgpu::VertexState {
                module: &shadow_shader,
                entry_point: Some("vs_main"),
                buffers: &[
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<Vertex>() as u64,
                        step_mode: wgpu::VertexStepMode::Vertex,
                        attributes: &SHADOW_VERTEX_ATTRS,
                    }),
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<ModelInstance>() as u64,
                        step_mode: wgpu::VertexStepMode::Instance,
                        attributes: &INSTANCE_ATTRS[..4],
                    }),
                ],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            // No color target: nothing is shaded here.
            fragment: None,
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                // Slope-scaled, because a face seen edge on from the light
                // covers an unbounded depth range in one texel. The normal
                // offset at sampling time covers the rest.
                bias: wgpu::DepthBiasState {
                    constant: 2,
                    slope_scale: 2.0,
                    clamp: 0.0,
                },
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });

        // The same pipeline blended, and not writing depth: a ghost has to
        // show what is behind it, and must not hide anything drawn after.
        let translucent_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("translucent model pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<Vertex>() as u64,
                        step_mode: wgpu::VertexStepMode::Vertex,
                        attributes: &VERTEX_ATTRS,
                    }),
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<ModelInstance>() as u64,
                        step_mode: wgpu::VertexStepMode::Instance,
                        attributes: &INSTANCE_ATTRS,
                    }),
                ],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                cull_mode: Some(wgpu::Face::Back),
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(false),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState {
                count: SAMPLES,
                ..wgpu::MultisampleState::default()
            },
            multiview_mask: None,
            cache: None,
        });

        // The same depth-only draw as the shadow pass, through the matrix
        // that looks straight down: what comes out is a height field of the
        // scene, which is what the occlusion is read from.
        let ao_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("occlusion pipeline"),
            layout: Some(&shadow_layout),
            vertex: wgpu::VertexState {
                module: &shadow_shader,
                entry_point: Some("vs_ao"),
                buffers: &[
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<Vertex>() as u64,
                        step_mode: wgpu::VertexStepMode::Vertex,
                        attributes: &SHADOW_VERTEX_ATTRS,
                    }),
                    Some(wgpu::VertexBufferLayout {
                        array_stride: std::mem::size_of::<ModelInstance>() as u64,
                        step_mode: wgpu::VertexStepMode::Instance,
                        attributes: &INSTANCE_ATTRS[..4],
                    }),
                ],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: None,
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                strip_index_format: None,
                front_face: wgpu::FrontFace::Ccw,
                // Both sides: a height field wants the top of everything,
                // including the underside of a mesh that has no top.
                cull_mode: None,
                polygon_mode: wgpu::PolygonMode::Fill,
                unclipped_depth: false,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: DEPTH_FORMAT,
                depth_write_enabled: Some(true),
                depth_compare: Some(wgpu::CompareFunction::Less),
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: wgpu::MultisampleState::default(),
            multiview_mask: None,
            cache: None,
        });

        let instance_capacity = 256;
        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("model instances"),
            size: (instance_capacity * std::mem::size_of::<ModelInstance>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        Self {
            pipeline,
            translucent_pipeline,
            shadow_pipeline,
            camera_buffer,
            bind_group,
            shadow_bind_group,
            shadow_view,
            ao_pipeline,
            ao_view,
            msaa: None,
            resolve: None,
            format,
            materials: Vec::new(),
            energy: Vec::new(),
            materials_uploaded: 0,
            material_buffer,
            energy_buffer,
            instance_buffer,
            instance_capacity,
            meshes: Vec::new(),
            depth: None,
        }
    }

    /// Uploads a mesh and returns the handle that draws it.
    pub fn upload(&mut self, device: &wgpu::Device, mesh: &MeshData) -> MeshId {
        let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some(&format!("{} vertices", mesh.name)),
            contents: bytemuck::cast_slice(&mesh.vertices),
            usage: wgpu::BufferUsages::VERTEX,
        });
        let indices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some(&format!("{} indices", mesh.name)),
            contents: bytemuck::cast_slice(&mesh.indices),
            usage: wgpu::BufferUsages::INDEX,
        });

        self.meshes.push(GpuMesh {
            vertices,
            indices,
            index_count: mesh.indices.len() as u32,
            base_color: mesh.base_color,
            min: mesh.min,
            max: mesh.max,
        });
        MeshId(self.meshes.len() - 1)
    }

    /// The material color a mesh came with, if any.
    pub fn base_color(&self, mesh: MeshId) -> Option<Color> {
        self.meshes.get(mesh.0).and_then(|m| m.base_color)
    }

    pub fn is_empty(&self) -> bool {
        self.meshes.is_empty()
    }

    #[allow(clippy::too_many_arguments)]
    pub fn render(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        encoder: &mut wgpu::CommandEncoder,
        width: u32,
        height: u32,
        clear_color: Color,
        view: &crate::views::View,
        clear: bool,
        suns: &Suns,
        ambient: &Ambient,
        draws: &ModelDrawList,
        lights: &[GpuLight],
    ) {
        let camera = &view.camera;
        let (opaque, translucent) = (&draws.opaque, &draws.translucent);
        // Fit the light's box to what is actually being drawn, so the map's
        // texels go where the scene is however the camera or scene moves.
        let bounds = scene_bounds(opaque, |mesh| {
            self.meshes.get(mesh.0).map(|m| (m.min, m.max))
        });
        // Nothing casting is a scene with no shadow to fit a map to, which is
        // the same case as nothing being drawn.
        let fit = bounds
            .zip(suns.shadowed)
            .map(|((min, max), sun)| {
                fit_light(min, max, sun.direction, sun.angle, SHADOW_MAP_SIZE as f32)
            })
            .unwrap_or(ShadowFit {
                light_view_proj: Mat4::IDENTITY,
                spread: 0.0,
                texel_world: 0.0,
                depth_span: 0.0,
                width: 0.0,
            });

        // The same fit looked at from straight above. Its depth is the height
        // of the scene, which is what tells a point how much of the sky is
        // shut out by whatever stands around it.
        let ao_fit = bounds
            .map(|(min, max)| fit_light(min, max, Vec3::Y, 0.0, AO_MAP_SIZE as f32))
            .unwrap_or(ShadowFit {
                light_view_proj: Mat4::IDENTITY,
                spread: 0.0,
                texel_world: 0.0,
                depth_span: 0.0,
                width: 0.0,
            });

        // An empty slot goes up as a light of no strength, which the shader
        // multiplies to nothing without needing to know it is missing.
        let sun = |slot: Option<Light>| {
            let light = slot.unwrap_or(Light::default().strength(0.0));
            let color = light.color();
            (
                [
                    light.direction.x,
                    light.direction.y,
                    light.direction.z,
                    light.strength,
                ],
                [color.x, color.y, color.z, 0.0],
            )
        };
        let (key_dir, key_color) = sun(suns.shadowed);
        let (rim_dir, rim_color) = sun(suns.unshadowed);
        let ambient_color = ambient.color();
        let uniform = CameraUniform {
            view_proj: camera.view_proj(view.aspect()).to_cols_array(),
            light_view_proj: fit.light_view_proj.to_cols_array(),
            ao_view_proj: ao_fit.light_view_proj.to_cols_array(),
            light_dir: key_dir,
            key_color,
            rim_dir,
            rim_color,
            ambient: [ambient_color.x, ambient_color.y, ambient_color.z, 0.0],
            eye: [camera.eye.x, camera.eye.y, camera.eye.z, 0.0],
            shadow: [
                fit.spread,
                fit.texel_world,
                1.0 / SHADOW_MAP_SIZE as f32,
                0.0,
            ],
            ao: [
                AO_REACH,
                ao_fit.depth_span,
                ambient.occlusion,
                ao_fit.width * AO_REACH,
            ],
            counts: [lights.len() as f32, 0.0, 0.0, 0.0],
            cluster: {
                let (scale, bias) = crate::clustered::slice_scale_bias(camera.near, camera.far);
                [scale, bias, width.max(1) as f32, height.max(1) as f32]
            },
        };
        queue.write_buffer(&self.camera_buffer, 0, bytemuck::bytes_of(&uniform));
        self.upload_shading(queue);

        // Both lists share one buffer: opaque first, then the ghosts.
        let instances: Vec<ModelInstance> = opaque
            .iter()
            .chain(translucent.iter())
            .map(|(_, instance)| *instance)
            .collect();
        if !instances.is_empty() {
            self.ensure_capacity(device, instances.len());
            queue.write_buffer(&self.instance_buffer, 0, bytemuck::cast_slice(&instances));
            // Ghosts cast neither shadow nor occlusion; they are a hint,
            // not a piece.
            self.shadow_pass(encoder, opaque);
            self.ao_pass(encoder, opaque);
        }

        let targets = self.targets(device, width, height);
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("model render pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                // Drawn into the multisampled image and resolved into the
                // single-sampled HDR one. The samples are kept as well: a
                // pass after this one draws into them, and resolves again.
                view: targets.color,
                resolve_target: Some(targets.resolve),
                depth_slice: None,
                // Only the first view of the frame clears: a clear takes the
                // whole attachment rather than the part being drawn, so a
                // second one would wipe the view beside it.
                ops: wgpu::Operations {
                    load: match clear {
                        true => wgpu::LoadOp::Clear(wgpu_color(clear_color)),
                        false => wgpu::LoadOp::Load,
                    },
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                view: targets.depth,
                depth_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(1.0),
                    store: wgpu::StoreOp::Store,
                }),
                stencil_ops: None,
            }),
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });

        if instances.is_empty() {
            return;
        }

        // Everything after this is confined to this view's corner of the
        // frame. The depth *was* cleared for the whole attachment above,
        // which is fine: the views before this one have already been drawn
        // and it is only their depth that goes.
        set_view(&mut pass, view, (width, height));

        pass.set_bind_group(0, &self.bind_group, &[]);
        pass.set_vertex_buffer(1, self.instance_buffer.slice(..));

        // Each list is sorted by mesh, so a run of equal ids is one call.
        pass.set_pipeline(&self.pipeline);
        self.draw_batches(&mut pass, opaque, 0);

        if !translucent.is_empty() {
            pass.set_pipeline(&self.translucent_pipeline);
            self.draw_batches(&mut pass, translucent, opaque.len());
        }
    }

    /// Draws every instance into the shadow map, depth only.
    fn shadow_pass(&self, encoder: &mut wgpu::CommandEncoder, draws: &[(MeshId, ModelInstance)]) {
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("shadow pass"),
            color_attachments: &[],
            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                view: &self.shadow_view,
                depth_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(1.0),
                    store: wgpu::StoreOp::Store,
                }),
                stencil_ops: None,
            }),
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });

        pass.set_pipeline(&self.shadow_pipeline);
        pass.set_bind_group(0, &self.shadow_bind_group, &[]);
        pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
        self.draw_batches(&mut pass, draws, 0);
    }

    /// Draws the scene from straight above, depth only: a height field.
    fn ao_pass(&self, encoder: &mut wgpu::CommandEncoder, draws: &[(MeshId, ModelInstance)]) {
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("occlusion pass"),
            color_attachments: &[],
            depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
                view: &self.ao_view,
                depth_ops: Some(wgpu::Operations {
                    load: wgpu::LoadOp::Clear(1.0),
                    store: wgpu::StoreOp::Store,
                }),
                stencil_ops: None,
            }),
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });

        pass.set_pipeline(&self.ao_pipeline);
        pass.set_bind_group(0, &self.shadow_bind_group, &[]);
        pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
        self.draw_batches(&mut pass, draws, 0);
    }

    /// Walks the runs of equal mesh ids in `draws`, one instanced call each.
    fn draw_batches<'pass>(
        &'pass self,
        pass: &mut wgpu::RenderPass<'pass>,
        draws: &[(MeshId, ModelInstance)],
        base: usize,
    ) {
        let mut start = 0usize;
        while start < draws.len() {
            let mesh_id = draws[start].0;
            let mut end = start + 1;
            while end < draws.len() && draws[end].0 == mesh_id {
                end += 1;
            }

            if let Some(mesh) = self.meshes.get(mesh_id.0) {
                pass.set_vertex_buffer(0, mesh.vertices.slice(..));
                pass.set_index_buffer(mesh.indices.slice(..), wgpu::IndexFormat::Uint32);
                pass.draw_indexed(
                    0..mesh.index_count,
                    0,
                    (base + start) as u32..(base + end) as u32,
                );
            }
            start = end;
        }
    }

    /// The images this frame is drawn into, remade whenever the window
    /// changes size.
    ///
    /// Public so a later pass can join this one: the grid draws into the same
    /// image and tests against the same depth, rather than starting a second
    /// pass that knows nothing about what is already standing there.
    pub fn targets(&mut self, device: &wgpu::Device, width: u32, height: u32) -> Targets<'_> {
        let size = wgpu::Extent3d {
            width: width.max(1),
            height: height.max(1),
            depth_or_array_layers: 1,
        };

        if !matches!(&self.depth, Some((w, h, _)) if *w == width && *h == height) {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("model depth"),
                size,
                mip_level_count: 1,
                // As many samples as the colour it is tested against.
                sample_count: SAMPLES,
                dimension: wgpu::TextureDimension::D2,
                format: DEPTH_FORMAT,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.depth = Some((width, height, view));
        }

        if !matches!(&self.msaa, Some((w, h, _)) if *w == width && *h == height) {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("model msaa"),
                size,
                mip_level_count: 1,
                sample_count: SAMPLES,
                dimension: wgpu::TextureDimension::D2,
                format: self.format,
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.msaa = Some((width, height, view));
        }

        if !matches!(&self.resolve, Some((w, h, _)) if *w == width && *h == height) {
            let texture = device.create_texture(&wgpu::TextureDescriptor {
                label: Some("model resolve"),
                size,
                mip_level_count: 1,
                // What the samples are averaged down to, so one of them.
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: self.format,
                // TEXTURE_BINDING because the tonemapper reads it back.
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                    | wgpu::TextureUsages::TEXTURE_BINDING,
                view_formats: &[],
            });
            let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
            self.resolve = Some((width, height, view));
        }

        Targets {
            color: &self.msaa.as_ref().expect("just created").2,
            resolve: &self.resolve.as_ref().expect("just created").2,
            depth: &self.depth.as_ref().expect("just created").2,
        }
    }

    /// Register `surface`, or find it if it is already there, and say where
    /// it landed.
    ///
    /// Registering is idempotent because a scene spawns the same material
    /// over and over -- thirty-two pieces sharing two surfaces -- and a table
    /// with thirty-two identical rows in it would cost thirty-two sets of
    /// energy tables to build and upload for no difference on screen.
    pub fn register_material(&mut self, surface: &OpenPbrSurface) -> MaterialId {
        let packed = material_of(surface);
        if let Some(index) = self.materials.iter().position(|m| *m == packed) {
            return MaterialId(index as u32);
        }
        if self.materials.len() == MAX_MATERIALS {
            log::error!("more than {MAX_MATERIALS} materials; reusing the first");
            return MaterialId(0);
        }

        // The tables are the surface integrated over incidence, so they are
        // built once here rather than per frame or per pixel.
        let tables = EnergyTables::compute(surface);
        self.energy
            .extend_from_slice(bytemuck::cast_slice(std::slice::from_ref(&tables)));
        self.materials.push(packed);
        MaterialId(self.materials.len() as u32 - 1)
    }

    /// Send whatever has been registered since the last frame, and this
    /// frame's lights.
    fn upload_shading(&mut self, queue: &wgpu::Queue) {
        if self.materials_uploaded < self.materials.len() {
            // Only the tail is new: the table never changes what is already
            // in it, so the rest of the buffer is still right.
            let first = self.materials_uploaded;
            let stride = std::mem::size_of::<OpenPbrMaterial>();
            queue.write_buffer(
                &self.material_buffer,
                (first * stride) as u64,
                bytemuck::cast_slice(&self.materials[first..]),
            );
            let floats = std::mem::size_of::<EnergyTables>() / std::mem::size_of::<f32>();
            queue.write_buffer(
                &self.energy_buffer,
                (first * floats * std::mem::size_of::<f32>()) as u64,
                bytemuck::cast_slice(&self.energy[first * floats..]),
            );
            self.materials_uploaded = self.materials.len();
        }
    }

    fn ensure_capacity(&mut self, device: &wgpu::Device, needed: usize) {
        if needed <= self.instance_capacity {
            return;
        }
        let capacity = needed.next_power_of_two();
        self.instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("model instances"),
            size: (capacity * std::mem::size_of::<ModelInstance>()) as u64,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        self.instance_capacity = capacity;
    }
}

/// Builder for a model in the world, spawned with
/// [`crate::AppState::spawn_model`].
///
/// ```no_run
/// # use codecraft::{AppState, render3d::Model, ui::Color};
/// # fn demo(app: &mut AppState) {
/// app.spawn_model(Model::new("chess_piece_king").at(0.0, 0.0, 0.0).color(Color::WHITE));
/// # }
/// ```
pub struct Model {
    pub mesh: String,
    pub transform: Transform,
    /// `None` keeps the color the mesh's own material came with.
    pub color: Option<Color>,
    /// How the surface takes light; a little sheen unless told otherwise.
    pub material: Material,
    /// The real material, when a scene has one. Wins over `material`, which
    /// is only a way of describing a surface in the two numbers the old
    /// shader took.
    pub surface: Option<OpenPbrSurface>,
}

impl Model {
    pub fn new(mesh: impl Into<String>) -> Self {
        Self {
            mesh: mesh.into(),
            transform: Transform::default(),
            color: None,
            material: Material::default(),
            surface: None,
        }
    }

    /// What this model is actually made of.
    pub fn surface(&self) -> OpenPbrSurface {
        self.surface
            .clone()
            .unwrap_or_else(|| self.material.to_openpbr())
    }

    pub fn at(mut self, x: f32, y: f32, z: f32) -> Self {
        self.transform.translation = Vec3::new(x, y, z);
        self
    }

    /// Rotation about the up axis, in radians.
    pub fn yaw(mut self, radians: f32) -> Self {
        self.transform.set_yaw(radians);
        self
    }

    pub fn scale(mut self, scale: f32) -> Self {
        self.transform.scale = scale;
        self
    }

    /// How polished the surface is: how bright a highlight it takes, and how
    /// tight.
    pub fn gloss(mut self, specular: f32, shininess: f32) -> Self {
        self.material = Material::gloss(specular, shininess);
        self
    }

    /// The whole material at once, for a surface neither default nor glossy.
    pub fn material(mut self, material: Material) -> Self {
        self.material = material;
        self
    }

    /// An OpenPBR surface: the whole material model, for anything that wants
    /// a coat, a metal, or something that light goes into.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, render3d::Model};
    /// # use codecraft::materials::openpbr::{Color3, OpenPbrSurface};
    /// # fn demo(app: &mut AppState) {
    /// app.spawn_model(Model::new("chess_piece_king").of(OpenPbrSurface {
    ///     base_color: Color3::new(0.9, 0.87, 0.8),
    ///     specular_roughness: 0.25,
    ///     coat_weight: 1.0,
    ///     coat_roughness: 0.05,
    ///     ..OpenPbrSurface::default()
    /// }));
    /// # }
    /// ```
    pub fn of(mut self, surface: OpenPbrSurface) -> Self {
        self.surface = Some(surface);
        self
    }

    pub fn color(mut self, color: Color) -> Self {
        self.color = Some(color);
        self
    }
}

/// Registers the 3D resources and the per-frame draw-list system.
pub struct Render3dPlugin;

impl Plugin for Render3dPlugin {
    fn build(&self, app: &mut Application) {
        app.insert_resource(Camera::default());
        app.init_resource::<crate::views::Views>();
        app.init_resource::<crate::ui::Profiler>();
        app.insert_resource(crate::sceneobjects::lights::Suns::default());
        app.insert_resource(crate::sceneobjects::lights::Ambient::default());
        app.insert_resource(MeshHandles::default());
        app.insert_resource(ModelDrawList::default());
        app.insert_resource(crate::sceneobjects::lights::LightDrawList::default());
        // Input the camera rig drives from. Owned by the host app and the UI
        // plugin, so these only fill in for a 3D app built without them — a
        // test, or a headless fit — and never overwrite what is there.
        app.init_resource::<crate::input::Keys>();
        app.init_resource::<crate::time::Time>();
        app.init_resource::<crate::ui::MouseInput>();
        app.init_resource::<crate::ui::CursorPosition>();
        app.init_resource::<crate::ui::PointerCapture>();
        app.init_resource::<crate::hid::GamepadState>();
        app.init_resource::<crate::hid::Gamepads>();
        // The rig reads this frame's wheel and click edges, so it has to run
        // before the UI schedule spends them.
        app.add_update_systems(
            crate::sceneobjects::cameras::orbit_camera_system
                // After the UI has said whether the pointer is over a panel,
                // and before the edges are spent.
                .after(crate::ui::systems::update_pointer_capture_system)
                .before(crate::ui::systems::clear_input_edge_system),
        );
        app.add_update_systems(collect_models_system);
        app.add_update_systems(crate::sceneobjects::lights::collect_lights_system);
        // Before anything reads `Lighting`: it is gathered from the world.
        app.add_update_systems(crate::sceneobjects::lights::collect_suns_system);
    }
}

/// Confines a pass to one view's corner of the frame.
///
/// Both the viewport and the scissor: the viewport is what maps clip space
/// onto those pixels, and the scissor is what stops anything -- a triangle
/// crossing the edge, a full-screen quad -- reaching past them into the view
/// beside it.
///
/// Clamped to the frame, because a viewport outside the attachment is a
/// validation error rather than a picture nobody sees.
pub(crate) fn set_view(pass: &mut wgpu::RenderPass<'_>, view: &crate::views::View, frame: (u32, u32)) {
    let (frame_width, frame_height) = (frame.0 as f32, frame.1 as f32);
    let x = view.rect.x.clamp(0.0, frame_width);
    let y = view.rect.y.clamp(0.0, frame_height);
    let width = view.rect.width.clamp(0.0, frame_width - x);
    let height = view.rect.height.clamp(0.0, frame_height - y);
    if width <= 0.0 || height <= 0.0 {
        return;
    }
    pass.set_viewport(x, y, width, height, 0.0, 1.0);
    pass.set_scissor_rect(x as u32, y as u32, width as u32, height as u32);
}