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
use std::sync::Arc;

use winit::{
    application::ApplicationHandler,
    event::{ElementState, KeyEvent, MouseButton, MouseScrollDelta, WindowEvent},
    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
    keyboard::PhysicalKey,
    window::{Window, WindowId},
};

use crate::audio::{Audio, Effect, LoopHandle, Voice};
use crate::capture;
use crate::clustered::Clusters;
use crate::control::{Command, Control, Request};
use crate::ecs::{Application as EcsApp, Bundle, Entity};
use crate::gizmos::{ActiveGrid, GizmosPlugin, GridRenderer, WireDrawList};
use crate::gpu::{FrameError, GpuContext};
use crate::hid::{GamepadState, Gamepads, HidPlugin, ps};
use crate::input::{KeyCode, Keys};
use crate::mesh::{MeshError, load_glb};
use crate::primitives::Primitive;
use crate::render3d::{
    Camera, MeshHandles, MeshId, MeshInstance, MeshRenderer, Model, ModelDrawList, Render3dPlugin,
};
use crate::scene::{self, Scene, SceneCommands, SceneEntity};
use crate::time::{Clock, Time};
use crate::tonemap::{self, Tonemap};
use crate::ui::{Color, CursorPosition, MouseInput, ScreenSize, UiPlugin, UiRenderer, Widget};

/// What the frame is cleared to before anything is drawn.
const BACKGROUND: Color = Color::srgb(0.05, 0.05, 0.07);

pub struct AppState {
    /// The window, when there is one. Headless runs without.
    pub window: Option<Arc<Window>>,
    pub gpu: GpuContext,
    pub ui_renderer: UiRenderer,
    pub mesh_renderer: MeshRenderer,
    pub grid_renderer: GridRenderer,
    pub wire_renderer: crate::gizmos::WireRenderer,
    /// Turns the HDR image the 3D passes leave into the frame that is shown.
    pub tonemap: Tonemap,
    /// Which lights reach which part of the frustum.
    pub clusters: Clusters,
    pub ecs: EcsApp,
    /// Sound effects, when the machine has an output for them.
    pub audio: Option<Audio>,
    /// Every controller plugged in. Drained every frame into the [`Gamepads`]
    /// resource, which is what a scene reads. Pads are found and dropped as
    /// they come and go, so this is a hub rather than one open device.
    pads: ps::Hub,
    scenes: SceneCommands,
    clock: Clock,
    time: Time,
    /// The loopback command port, when one was asked for.
    control: Option<Control>,
    /// A screenshot asked for, waiting on the next frame.
    pending_capture: Option<(std::path::PathBuf, Request)>,
    /// Keys pressed over the control port, to let go of at the end of the
    /// frame they were pressed in.
    keys_to_release: Vec<crate::input::KeyCode>,
    /// Set when the control port clicked, so the button can be let go at the
    /// end of the frame: a click is a press and a release.
    click_to_release: bool,
    /// Set when the control port asks the game to stop.
    quit: bool,
}

impl AppState {
    pub fn new(window: Arc<Window>) -> Self {
        let gpu = GpuContext::new(window.clone());
        Self::with_gpu(gpu, Some(window))
    }

    /// An app with no window: nothing is shown, nothing takes focus, and
    /// screenshots come off the GPU as they do with one.
    pub fn offscreen(width: u32, height: u32) -> Self {
        Self::with_gpu(GpuContext::offscreen(width, height), None)
    }

    fn with_gpu(gpu: GpuContext, window: Option<Arc<Window>>) -> Self {
        // The world is drawn in linear light, into a floating-point image;
        // only the tonemapper and the UI touch the frame itself.
        let ui_renderer = UiRenderer::new(&gpu.device, gpu.format());
        // The clusters own the light buffer the shading pass reads, so they
        // are built first.
        let clusters = Clusters::new(&gpu.device);
        let mesh_renderer = MeshRenderer::new(&gpu.device, tonemap::HDR_FORMAT, &clusters);
        let grid_renderer = GridRenderer::new(&gpu.device, tonemap::HDR_FORMAT);
        let wire_renderer = crate::gizmos::WireRenderer::new(&gpu.device, tonemap::HDR_FORMAT);
        let tonemap = Tonemap::new(&gpu.device, gpu.format());

        let mut ecs = EcsApp::new();
        ecs.add_plugin(UiPlugin);
        ecs.add_plugin(Render3dPlugin);
        ecs.add_plugin(GizmosPlugin);
        ecs.add_plugin(HidPlugin);
        ecs.add_plugin(crate::dev::DevPlugin);
        ecs.world.insert_resource(ScreenSize {
            width: gpu.width() as f32,
            height: gpu.height() as f32,
        });

        ecs.world.insert_resource(Keys::default());

        let scenes = SceneCommands::new();
        let time = Time::default();
        ecs.world.insert_resource(scenes.clone());
        ecs.world.insert_resource(time);

        Self {
            window,
            gpu,
            ui_renderer,
            mesh_renderer,
            grid_renderer,
            wire_renderer,
            tonemap,
            clusters,
            ecs,
            audio: Audio::new(),
            pads: ps::Hub::new(),
            scenes,
            clock: Clock::new(),
            time,
            control: Control::from_env(),
            pending_capture: None,
            keys_to_release: Vec::new(),
            click_to_release: false,
            quit: false,
        }
    }

    /// Takes anything asked for over the control port. Screenshots are held
    /// until the frame they are supposed to capture has been drawn.
    fn take_control_requests(&mut self) {
        let Some(control) = self.control.as_ref() else {
            return;
        };
        while let Some(request) = control.poll() {
            match request.command().clone() {
                Command::Screenshot { path } => {
                    if let Some((_, waiting)) = self.pending_capture.take() {
                        waiting.answer(Err("replaced by a later screenshot".into()));
                    }
                    self.pending_capture = Some((path, request));
                }
                Command::Key { code } => {
                    // Straight into the same state the window writes to, so
                    // it reads exactly like somebody at the keyboard. Held
                    // for one frame, which is what a press is.
                    self.ecs.world.resource_mut::<Keys>().press(code, false);
                    self.keys_to_release.push(code);
                    request.answer(Ok(format!("{code:?}")));
                }
                Command::Down { code } => {
                    // Held until `Up`: nothing queues a release.
                    self.ecs.world.resource_mut::<Keys>().press(code, false);
                    request.answer(Ok(format!("{code:?} down")));
                }
                Command::Up { code } => {
                    self.ecs.world.resource_mut::<Keys>().release(code);
                    request.answer(Ok(format!("{code:?} up")));
                }
                Command::Cursor { x, y } => {
                    self.ecs.world.insert_resource(CursorPosition { x, y });
                    request.answer(Ok(format!("{x} {y}")));
                }
                Command::Click { at } => {
                    if let Some((x, y)) = at {
                        self.ecs.world.insert_resource(CursorPosition { x, y });
                    }
                    // The same edge the window reports, spent by
                    // `clear_input_edge_system` at the end of the frame.
                    let mut mouse = self.ecs.world.resource_mut::<MouseInput>();
                    mouse.left_down = true;
                    mouse.just_pressed = true;
                    self.click_to_release = true;
                    request.answer(Ok("click".into()));
                }
                Command::Press { at } => {
                    if let Some((x, y)) = at {
                        self.ecs.world.insert_resource(CursorPosition { x, y });
                    }
                    let mut mouse = self.ecs.world.resource_mut::<MouseInput>();
                    mouse.left_down = true;
                    mouse.just_pressed = true;
                    // Held, not spent: a `release` is what lets it go.
                    request.answer(Ok("press".into()));
                }
                Command::Release => {
                    let mut mouse = self.ecs.world.resource_mut::<MouseInput>();
                    mouse.left_down = false;
                    mouse.just_released = true;
                    request.answer(Ok("release".into()));
                }
                Command::Quit => {
                    self.quit = true;
                    request.answer(Ok("stopping".into()));
                }
            }
        }
    }

    pub fn width(&self) -> f32 {
        self.gpu.width() as f32
    }

    pub fn height(&self) -> f32 {
        self.gpu.height() as f32
    }

    /// Frame timing as of the current frame.
    pub fn time(&self) -> Time {
        self.time
    }

    /// A handle for requesting scene changes, clonable into UI callbacks.
    pub fn scenes(&self) -> SceneCommands {
        self.scenes.clone()
    }

    /// Queues `scene` as the next active scene; applied at the next frame
    /// boundary. See [`SceneCommands`] for requesting one from a callback.
    pub fn change_scene(&self, scene: impl Scene) {
        self.scenes.change(scene);
    }

    /// Queues `scene` to take over in `seconds`, leaving this one up until
    /// then, so a scene that just waits needs no timer of its own.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, scene::Scene};
    /// # struct MainMenu;
    /// # impl Scene for MainMenu {}
    /// # fn demo(app: &mut AppState) {
    /// app.change_scene_after(2.0, MainMenu);
    /// # }
    /// ```
    pub fn change_scene_after(&self, seconds: f32, scene: impl Scene) {
        self.scenes.change_after(seconds, scene);
    }

    /// Spawns a UI widget, laid out for the current window size, and returns
    /// whatever that widget hands back (see [`Widget::Output`]).
    ///
    /// ```no_run
    /// # use codecraft::{AppState, ui::{Button, Panel}};
    /// # fn demo(app: &mut AppState) {
    /// let menu = app.spawn(Panel::new("MainMenu").add(Button::new("QUIT", || std::process::exit(0))));
    /// let quit_button = menu.buttons[0];
    /// # }
    /// ```
    pub fn spawn<W: Widget>(&mut self, widget: W) -> W::Output {
        let (width, height) = (self.width(), self.height());
        widget.spawn(&mut self.ecs.world, width, height)
    }

    /// Uploads every named mesh in a `.glb`, ready for
    /// [`AppState::spawn_model`] to place by name.
    ///
    /// ```no_run
    /// # use codecraft::AppState;
    /// # fn demo(app: &mut AppState) {
    /// let glb = std::fs::read("scene.glb").unwrap();
    /// app.load_meshes(&glb).unwrap();
    /// # }
    /// ```
    /// Meshes already loaded under the same name are left alone, so a scene
    /// can ask for its assets on every entry without re-uploading them.
    pub fn load_meshes(&mut self, glb: &[u8]) -> Result<(), MeshError> {
        let mut handles = self.ecs.world.resource::<MeshHandles>().clone();
        for mesh in load_glb(glb)? {
            if handles.get(&mesh.name).is_some() {
                continue;
            }
            let id = self.mesh_renderer.upload(&self.gpu.device, &mesh);
            log::debug!("loaded mesh {:?} as {id:?}", mesh.name);
            handles.insert(mesh.name, id);
        }
        self.ecs.world.insert_resource(handles);
        Ok(())
    }

    /// The handle for a mesh loaded by [`AppState::load_meshes`].
    pub fn mesh(&self, name: &str) -> Option<MeshId> {
        self.ecs.world.resource::<MeshHandles>().get(name)
    }

    /// Places a model in the world. Its color defaults to the material the
    /// mesh was exported with.
    ///
    /// An unknown mesh name is reported and leaves an entity that draws
    /// nothing, rather than taking the game down mid-scene.
    pub fn spawn_model(&mut self, model: Model) -> Entity {
        let Some(mesh) = self.mesh(&model.mesh) else {
            log::error!(
                "no mesh named {:?}; loaded meshes: {:?}",
                model.mesh,
                self.ecs
                    .world
                    .resource::<MeshHandles>()
                    .names()
                    .collect::<Vec<_>>(),
            );
            return self.spawn_entity(model.transform);
        };

        let color = model
            .color
            .or_else(|| self.mesh_renderer.base_color(mesh))
            .unwrap_or(Color::WHITE);
        let material = self.mesh_renderer.register_material(&model.surface());
        self.spawn_entity((
            model.transform,
            MeshInstance {
                mesh,
                color,
                material,
            },
        ))
    }

    /// Places a shape the code builds for itself — see [`crate::primitives`].
    ///
    /// The mesh is uploaded the first time a given size is asked for and
    /// shared after that, so a scene can spawn a hundred unit cubes without
    /// a hundred vertex buffers.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, primitives};
    /// # fn demo(app: &mut AppState) {
    /// app.spawn_primitive(primitives::Box::cube(1.0));
    /// # }
    /// ```
    pub fn spawn_primitive<P: Primitive>(&mut self, primitive: P) -> Entity {
        let name = primitive.name();
        let mesh = match self.mesh(&name) {
            Some(mesh) => mesh,
            None => {
                let data = primitive.build();
                let mesh = self.mesh_renderer.upload(&self.gpu.device, &data);
                let mut handles = self.ecs.world.resource::<MeshHandles>().clone();
                handles.insert(name, mesh);
                self.ecs.world.insert_resource(handles);
                mesh
            }
        };

        let (transform, color) = primitive.placement();
        let color = color
            .or_else(|| self.mesh_renderer.base_color(mesh))
            .unwrap_or(Color::WHITE);
        let material = self
            .mesh_renderer
            .register_material(&crate::material::Material::default().to_openpbr());
        self.spawn_entity((
            transform,
            MeshInstance {
                mesh,
                color,
                // A primitive is a stand-in shape; it takes the default sheen
                // until somebody says otherwise.
                material,
            },
        ))
    }

    /// The colour a loaded mesh came with, for putting one back after it has
    /// been tinted.
    pub fn mesh_base_color(&self, name: &str) -> Option<Color> {
        self.mesh(name)
            .and_then(|id| self.mesh_renderer.base_color(id))
    }

    /// Sets the eye the 3D scene is drawn from.
    pub fn set_camera(&mut self, camera: Camera) {
        self.ecs.world.insert_resource(camera);
        self.set_views(crate::views::Views::one(camera));
    }

    /// Files a span that was timed with a plain `Instant`.
    fn record_span(&mut self, name: &'static str, start: std::time::Instant) {
        let taken = start.elapsed();
        let mut profiler = self.ecs.world.resource_mut::<crate::ui::Profiler>();
        let from = profiler.since_frame_start(start);
        profiler.record(crate::ui::Span {
            name: name.to_string(),
            lane: crate::ui::Lane::Cpu,
            start: from,
            end: from + taken.as_secs_f64() * 1000.0,
        });
    }

    /// Runs `work`, and files how long it took as a CPU span.
    ///
    /// A method rather than the `Timing` guard, because the guard borrows the
    /// profiler and almost everything worth timing here needs the whole app.
    fn timed<T>(&mut self, name: &'static str, work: impl FnOnce(&mut Self) -> T) -> T {
        let start = std::time::Instant::now();
        let out = work(self);
        let taken = start.elapsed();
        let mut profiler = self.ecs.world.resource_mut::<crate::ui::Profiler>();
        let from = profiler.since_frame_start(start);
        profiler.record(crate::ui::Span {
            name: name.to_string(),
            lane: crate::ui::Lane::Cpu,
            start: from,
            end: from + taken.as_secs_f64() * 1000.0,
        });
        out
    }

    /// Where the world is drawn, and from how many places.
    ///
    /// One view is the ordinary case and what [`set_camera`](Self::set_camera)
    /// leaves behind. Two side by side is a game with two people at one
    /// screen; see [`crate::Views`].
    ///
    /// ```no_run
    /// # use codecraft::{AppState, Camera, Views};
    /// # fn demo(app: &mut AppState, one: Camera, two: Camera) {
    /// let (w, h) = (app.width(), app.height());
    /// app.set_views(Views::split(one, two, w, h).with_minimap(Camera::default()));
    /// # }
    /// ```
    pub fn set_views(&mut self, views: crate::views::Views) {
        self.ecs.world.insert_resource(views);
    }

    /// What the world is being drawn from this frame, with the rectangles
    /// already fitted to the window.
    pub fn views(&self) -> crate::views::Views {
        self.ecs.world.resource::<crate::views::Views>().clone()
    }

    /// Spawns a scene-owned entity: like `world.spawn`, but tagged with
    /// [`SceneEntity`] so it is cleaned up on a scene change.
    pub fn spawn_entity(&mut self, bundle: impl Bundle) -> Entity {
        self.ecs.world.spawn((bundle, SceneEntity)).id()
    }

    /// Adds components to an entity that is already there.
    ///
    /// For the things a scene knows about an object that the thing that
    /// spawned it does not -- what to call it in the outliner, most of all,
    /// which `spawn_model` cannot know because it only sees a mesh name.
    pub fn insert(&mut self, entity: Entity, bundle: impl Bundle) {
        if let Ok(mut entity) = self.ecs.world.get_entity_mut(entity) {
            entity.insert(bundle);
        }
    }

    /// Reads a component off an entity, for a scene that has to ask what it
    /// put somewhere -- a light's own settings, to draw a gizmo for it.
    pub fn get<C: bevy_ecs::component::Component>(&self, entity: Entity) -> Option<&C> {
        self.ecs.world.get::<C>(entity)
    }

    /// Changes a component on an entity a scene spawned — a heading's text,
    /// a button's label.
    ///
    /// Does nothing if the entity is gone or has no such component, so a
    /// scene holding a stale handle cannot bring the game down.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, ecs::Entity, ui::HeadingText};
    /// # fn demo(app: &mut AppState, status: Entity) {
    /// app.edit::<HeadingText>(status, |heading| heading.text = "SEEKING".into());
    /// # }
    /// ```
    pub fn edit<C: bevy_ecs::component::Component<Mutability = bevy_ecs::component::Mutable>>(
        &mut self,
        entity: Entity,
        change: impl FnOnce(&mut C),
    ) {
        if let Some(mut component) = self.ecs.world.get_mut::<C>(entity) {
            change(&mut component);
        }
    }

    /// Removes a single entity — for UI a scene spawns and takes down again,
    /// like a pause menu.
    pub fn despawn(&mut self, entity: Entity) {
        self.ecs.world.despawn(entity);
    }

    /// Despawns every entity of the outgoing scene, leaving resources (input,
    /// screen size, timing) intact. Called on a scene change.
    pub fn clear_scene(&mut self) {
        scene::clear_scene(&mut self.ecs.world);
    }

    /// Advances the frame clock, republishes [`Time`] into the world and
    /// counts the frame off any delayed scene change. Called once per frame.
    pub fn tick_time(&mut self) {
        // The frame starts here, not in `render`: the gamepads are polled
        // below, and a span timed against the *previous* frame's origin lands
        // sixteen milliseconds up the chart and makes the frame look twice as
        // long as it was.
        self.ecs
            .world
            .resource_mut::<crate::ui::Profiler>()
            .begin_frame();
        self.time = self.clock.tick();
        self.ecs.world.insert_resource(self.time);
        self.scenes.tick(self.time.delta);
        // Timed by name because this is where a stutter lived once: the
        // controller scan used to enumerate the machine's HID devices here,
        // which costs about a hundred milliseconds. See `hid::ps::RESCAN`.
        self.timed("gamepads", |app| app.poll_gamepad());
    }

    /// Drains every controller's pending reports and republishes what they are
    /// sending. Called once per frame, before the scene is updated, so a scene
    /// reads the pads as they are now rather than as they were last frame.
    ///
    /// This is also where a pad plugged in mid-game is picked up and one
    /// unplugged is let go: see [`ps::Hub::poll`].
    fn poll_gamepad(&mut self) {
        let pads: Vec<GamepadState> = self
            .pads
            .poll()
            .iter()
            .map(|pad| GamepadState {
                connected: true,
                model: Some(pad.model()),
                state: *pad.state(),
            })
            .collect();
        // The first one is "the" controller, for everything that only wants
        // one -- the camera rig, the debug overlay, a one-player game.
        let first = pads.first().copied().unwrap_or_default();
        self.ecs.world.insert_resource(Gamepads(pads));
        self.ecs.world.insert_resource(first);
    }

    /// Tells the pad in a seat what to do with itself: rumble, the shape of
    /// its triggers, the colour of its light. Nothing happens for a seat
    /// with no pad in it, and a pad is only written to when this differs
    /// from the last thing it was told. See [`hid::Feedback`].
    ///
    /// ```no_run
    /// # use codecraft::{AppState, hid::{Feedback, Trigger}};
    /// # fn demo(app: &mut AppState, kick: f32) {
    /// app.feel(0, &Feedback {
    ///     strong: kick,
    ///     right: Trigger::Weapon { from: 2, to: 6, strength: 8 },
    ///     ..Feedback::default()
    /// });
    /// # }
    /// ```
    pub fn feel(&mut self, seat: usize, feedback: &crate::hid::Feedback) {
        self.pads.feel(seat, feedback);
    }

    /// Plays one of the engine's own sounds out of a seat's pad -- its
    /// speaker at `speaker`, its haptic actuators at `haptic`, both nought
    /// to one -- so a player hears their gun in their hands and feels it
    /// too. Silent for a seat whose pad has no sound card the machine can
    /// tell apart from the others, and on a machine with no audio at all.
    pub fn play_effect_on(&mut self, seat: usize, effect: Effect, speaker: f32, haptic: f32) {
        let Some(key) = self.pads.key(seat) else {
            return;
        };
        if let Some(audio) = self.audio.as_mut() {
            audio.play_effect_on(&key, effect, speaker, haptic);
        }
    }

    /// Starts a voice on a seat's pad, the way [`start_loop`](Self::start_loop)
    /// does on the speakers, and hands back the handle that turns it; `None`
    /// when the seat has no pad that can play.
    #[must_use = "a loop stops when its last handle is dropped"]
    pub fn start_loop_on(
        &mut self,
        seat: usize,
        voice: Voice,
        speaker: f32,
        haptic: f32,
    ) -> Option<LoopHandle> {
        let key = self.pads.key(seat)?;
        self.audio
            .as_mut()
            .and_then(|audio| audio.start_loop_on(&key, voice, speaker, haptic))
    }

    /// What the controller is sending this frame.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, hid::ps::button};
    /// # fn demo(app: &mut AppState) {
    /// if app.gamepad().held(button::CROSS) {
    ///     // thrust
    /// }
    /// # }
    /// ```
    pub fn gamepad(&self) -> GamepadState {
        *self.ecs.world.resource::<GamepadState>()
    }

    /// Every controller plugged in this frame.
    ///
    /// ```no_run
    /// # use codecraft::AppState;
    /// # fn demo(app: &mut AppState) {
    /// let pads = app.gamepads();
    /// for player in 0..2 {
    ///     let pad = pads.player(player);
    ///     // pad.connected says whether that seat has one yet
    /// }
    /// # }
    /// ```
    pub fn gamepads(&self) -> Gamepads {
        self.ecs.world.resource::<Gamepads>().clone()
    }

    pub fn resize(&mut self, width: u32, height: u32) {
        if width == 0 || height == 0 {
            return;
        }
        self.gpu.resize(width, height);
        self.ecs.world.insert_resource(ScreenSize {
            width: width as f32,
            height: height as f32,
        });
    }

    pub fn set_cursor(&mut self, x: f32, y: f32) {
        self.ecs.world.insert_resource(CursorPosition { x, y });
    }

    /// Keyboard state for this frame.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, KeyCode};
    /// # fn demo(app: &mut AppState) {
    /// if app.keys().just_pressed(KeyCode::Escape) {
    ///     // toggle a menu
    /// }
    /// # }
    /// ```
    pub fn keys(&self) -> &Keys {
        self.ecs.world.resource::<Keys>()
    }

    pub fn set_key(&mut self, key: KeyCode, down: bool, repeat: bool) {
        let mut keys = self.ecs.world.resource_mut::<Keys>();
        if down {
            keys.press(key, repeat);
        } else {
            keys.release(key);
        }
    }

    pub fn set_mouse_left(&mut self, down: bool) {
        let mut mouse = self.ecs.world.resource_mut::<MouseInput>();
        let was_down = mouse.left_down;
        mouse.left_down = down;
        if down {
            mouse.just_pressed = true;
        } else if was_down {
            mouse.just_released = true;
        }
    }

    pub fn set_mouse_right(&mut self, down: bool) {
        self.ecs.world.resource_mut::<MouseInput>().right_down = down;
    }

    /// Adds wheel clicks to this frame's total, positive away from the user.
    /// Added rather than set, because several events can arrive between two
    /// frames and a flick of the wheel is all of them.
    pub fn add_scroll(&mut self, clicks: f32) {
        self.ecs.world.resource_mut::<MouseInput>().scroll += clicks;
    }

    /// Plays one clip from a loaded sound set. Silent when the machine has
    /// no audio output, so a caller never has to check.
    ///
    /// ```no_run
    /// # use codecraft::AppState;
    /// # fn demo(app: &mut AppState) {
    /// app.play_sound("piece_up");
    /// # }
    /// ```
    pub fn play_sound(&mut self, set: &str) {
        if let Some(audio) = self.audio.as_mut() {
            audio.play(set);
        }
    }

    /// Loads a set of clips under a name, for [`AppState::play_sound`].
    pub fn load_sounds(&mut self, set: &str, clips: &[&'static [u8]]) {
        if let Some(audio) = self.audio.as_mut() {
            audio.load_set(set, clips);
        }
    }

    /// Plays a sound the engine makes itself — a gun, a hit, an explosion —
    /// with nothing to load first. Silent when the machine has no audio
    /// output.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, Effect};
    /// # fn demo(app: &mut AppState) {
    /// app.play_effect(Effect::Gunshot);
    /// # }
    /// ```
    pub fn play_effect(&mut self, effect: Effect) {
        if let Some(audio) = self.audio.as_mut() {
            audio.play_effect(effect);
        }
    }

    /// Starts a sound that runs for as long as its handle is held — an
    /// engine — and hands back the handle that turns it. Dropping the last
    /// handle stops the sound, so it lives where the thing making the noise
    /// does. `None` when the machine has no audio output, so a game keeps an
    /// `Option<LoopHandle>` and drives it through `if let`, which is the
    /// whole of what silence costs it.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, Voice};
    /// # fn demo(app: &mut AppState, throttle: f32) {
    /// let engine = app.start_loop(Voice::Engine);
    /// if let Some(engine) = &engine {
    ///     engine.set(1.0 + throttle, 0.5 + 0.5 * throttle);
    /// }
    /// # }
    /// ```
    #[must_use = "a loop stops when its last handle is dropped"]
    pub fn start_loop(&mut self, voice: Voice) -> Option<LoopHandle> {
        self.audio.as_mut().map(|audio| audio.start_loop(voice))
    }

    /// Turns sound off without unloading anything.
    pub fn set_muted(&mut self, muted: bool) {
        if let Some(audio) = self.audio.as_mut() {
            audio.set_muted(muted);
        }
    }

    /// Asks the window to draw another frame. Headless draws on its own
    /// schedule, so this does nothing there.
    pub fn request_redraw(&self) {
        if let Some(window) = self.window.as_ref() {
            window.request_redraw();
        }
    }

    /// Whether the control port asked the game to stop.
    pub fn should_quit(&self) -> bool {
        self.quit
    }

    /// Where the cursor is, in pixels from the window's top-left.
    pub fn cursor(&self) -> (f32, f32) {
        let cursor = self.ecs.world.resource::<CursorPosition>();
        (cursor.x, cursor.y)
    }

    /// Mouse button state for this frame.
    pub fn mouse(&self) -> MouseInput {
        *self.ecs.world.resource::<MouseInput>()
    }

    /// The eye the 3D scene is drawn from.
    pub fn camera(&self) -> Camera {
        *self.ecs.world.resource::<Camera>()
    }

    /// Whether dev mode is on — F12 toggles it.
    ///
    /// What to show while it is on is the scene's own business: a grid, a
    /// camera that can be flown, gizmos on the lights.
    pub fn dev_mode(&self) -> bool {
        self.ecs.world.resource::<crate::dev::DevMode>().is_on()
    }

    /// Turns dev mode on or off, badge and all: what F12 does, for a scene
    /// that wants to start with the working showing.
    pub fn set_dev_mode(&mut self, on: bool) {
        crate::dev::set(&mut self.ecs.world, on);
    }

    /// The directional lights the scene is being shaded by, as the renderer
    /// last gathered them.
    ///
    /// Read-only, and derived: to *change* what a scene is lit by, spawn the
    /// lights it should have. They are ordinary entities.
    ///
    /// ```no_run
    /// # use codecraft::{AppState, Light};
    /// # fn demo(app: &mut AppState) {
    /// app.spawn_entity((
    ///     Light::default().temperature(3200.0),
    ///     Light::item("Key Light"),
    /// ));
    /// # }
    /// ```
    pub fn suns(&self) -> crate::sceneobjects::lights::Suns {
        *self.ecs.world.resource::<crate::sceneobjects::lights::Suns>()
    }

    /// The light with no direction: the sky, and the room.
    pub fn ambient(&self) -> crate::sceneobjects::lights::Ambient {
        *self
            .ecs
            .world
            .resource::<crate::sceneobjects::lights::Ambient>()
    }

    /// Changes it. Unlike the directional lights this is not a thing standing
    /// anywhere, so there is nothing to spawn and it stays a setting.
    pub fn set_ambient(&mut self, ambient: crate::sceneobjects::lights::Ambient) {
        self.ecs.world.insert_resource(ambient);
    }

    /// The ray under the cursor, for working out what it is over.
    pub fn cursor_ray(&self) -> crate::render3d::Ray {
        self.camera()
            .ray(self.cursor(), self.width(), self.height())
    }

    /// Runs the ECS update (relayout, interaction, click dispatch), then
    /// draws the world and the UI over it.
    pub fn render(&mut self) -> Result<(), FrameError> {
        self.timed("ecs", |app| app.ecs.update());

        // Timed, and named for what it is: acquiring the next image blocks
        // until the display is ready for one, so on a machine keeping up this
        // is nearly the whole frame and the work is the sliver around it. A
        // chart with sixteen unaccounted milliseconds in it invites a hunt
        // for a stall that is really just the screen's refresh rate.
        let acquire_started = std::time::Instant::now();
        let frame = self.gpu.begin_frame()?;
        self.record_span("wait for display", acquire_started);
        let (width, height) = (self.gpu.width(), self.gpu.height());

        // Where the world is drawn, and from how many places. Fitted to the
        // frame here rather than by the scene: a scene says "two side by
        // side" once, and how many pixels that is changes with the window.
        let mut views = self.ecs.world.resource::<crate::views::Views>().clone();
        views.fit(width as f32, height as f32);
        // Put the fitted rects back, so anything asking what is under the
        // pointer this frame reads the same rectangles that were drawn.
        self.ecs.world.insert_resource(views.clone());
        // The camera resource follows the first view, for everything that
        // only wants "the" camera: picking, the grid, a one-view game.
        let camera = views.camera();
        self.ecs.world.insert_resource(camera);
        let suns = *self
            .ecs
            .world
            .resource::<crate::sceneobjects::lights::Suns>();
        let ambient = *self
            .ecs
            .world
            .resource::<crate::sceneobjects::lights::Ambient>();
        let lights = self
            .ecs
            .world
            .resource::<crate::sceneobjects::lights::LightDrawList>()
            .0
            .clone();
        let grid = self.ecs.world.resource::<ActiveGrid>().0;
        let lines = std::mem::take(&mut self.ecs.world.resource_mut::<WireDrawList>().0);

        // One submit per view, not one encoder for all of them.
        //
        // The camera uniform and the cluster grid are both sent with
        // `queue.write_buffer`, and those land before the submit they were
        // written for rather than in the middle of it. Two views encoded
        // together would therefore both be drawn with whichever camera was
        // written last -- the same picture twice, side by side. A submit
        // between them is what makes each view's write its own.
        let views_started = std::time::Instant::now();
        for (index, view) in views.iter().enumerate() {
            let mut encoder = self.gpu.create_encoder("view encoder");

            // Culled against this view's own frustum: the left player's lights
            // are not the right player's, and a grid sized for the whole frame
            // would put a half-width view's fragments in the wrong cells.
            self.clusters.prepare(
                &self.gpu.queue,
                &lights,
                view.camera.view(),
                view.camera.projection(view.aspect()),
                view.rect.width.max(1.0) as u32,
                view.rect.height.max(1.0) as u32,
                view.camera.near,
                view.camera.far,
            );
            self.clusters.cull(&mut encoder);

            self.mesh_renderer.render(
                &self.gpu.device,
                &self.gpu.queue,
                &mut encoder,
                width,
                height,
                BACKGROUND,
                view,
                index == 0,
                &suns,
                &ambient,
                self.ecs.world.resource::<ModelDrawList>(),
                &lights,
            );

            // The ground grid goes on after the models, testing against the
            // depth they left so that anything standing on it hides the lines
            // under it.
            if let Some(grid) = grid {
                let targets = self.mesh_renderer.targets(&self.gpu.device, width, height);
                self.grid_renderer.render(
                    &self.gpu.queue,
                    &mut encoder,
                    targets.color,
                    targets.resolve,
                    targets.depth,
                    width,
                    height,
                    view,
                    &grid,
                );
            }

            // Gizmos last of the 3D passes: they mark what is already there,
            // so they are drawn over it and against its depth.
            if !lines.is_empty() {
                let targets = self.mesh_renderer.targets(&self.gpu.device, width, height);
                self.wire_renderer.render(
                    &self.gpu.device,
                    &self.gpu.queue,
                    &mut encoder,
                    targets.color,
                    targets.resolve,
                    targets.depth,
                    width,
                    height,
                    view,
                    &lines,
                );
            }

            self.gpu.queue.submit(std::iter::once(encoder.finish()));
        }
        // Put the buffer back for the collector to fill again.
        self.ecs.world.resource_mut::<WireDrawList>().0 = lines;
        self.record_span("views", views_started);

        let mut encoder = self.gpu.create_encoder("chessrs frame encoder");

        // Everything above drew light; this is where it becomes an image.
        // The UI comes after it on purpose: a label is not lit by anything.
        let (width, height) = (self.gpu.width(), self.gpu.height());
        let hdr = self
            .mesh_renderer
            .targets(&self.gpu.device, width, height)
            .resolve
            .clone();
        self.tonemap.render(
            &self.gpu.device,
            &mut encoder,
            &hdr,
            width,
            height,
            &frame.view,
        );

        // Any icon a panel asked for this frame is rasterised by now; send
        // the atlas if it grew.
        {
            let mut atlas = self.ecs.world.resource_mut::<crate::ui::Atlas>();
            self.ui_renderer.upload_atlas(&self.gpu.queue, &mut atlas);
        }

        // The chart goes on the end of this frame's quads, over everything
        // else: it is a thing you look at *while* the game runs.
        let mut quads = self.ecs.world.resource::<crate::ui::UiDrawList>().0.clone();
        // Drawing it needs the profiler, the font and the atlas at once, and
        // the world will only lend out one at a time. Taking two out and
        // putting them back is the plain way to say that.
        if let (Some(profiler), Some(font)) = (
            self.ecs.world.remove_resource::<crate::ui::Profiler>(),
            self.ecs.world.remove_resource::<crate::ui::Font>(),
        ) {
            let mut atlas = self.ecs.world.resource_mut::<crate::ui::Atlas>();
            crate::ui::components::profiler::draw(
                &profiler,
                &mut quads,
                &mut atlas,
                font.face(),
                width as f32,
                height as f32,
            );
            drop(atlas);
            self.ecs.world.insert_resource(profiler);
            self.ecs.world.insert_resource(font);
        }
        let quads = &quads;
        self.ui_renderer.render(
            &self.gpu.device,
            &self.gpu.queue,
            &mut encoder,
            &frame.view,
            self.gpu.width() as f32,
            self.gpu.height() as f32,
            quads,
        );

        let staged = self.pending_capture.as_ref().map(|_| {
            capture::stage(
                &self.gpu.device,
                &mut encoder,
                frame.texture(),
                self.gpu.width(),
                self.gpu.height(),
            )
        });

        let submit_started = std::time::Instant::now();
        self.gpu.submit(encoder);
        self.record_span("submit", submit_started);

        if let (Some(staged), Some((path, request))) = (staged, self.pending_capture.take()) {
            let answer = match capture::write_png(&self.gpu, staged, &path) {
                Ok(()) => Ok(path.display().to_string()),
                Err(error) => Err(error.to_string()),
            };
            request.answer(answer);
        }

        let present_started = std::time::Instant::now();
        self.gpu.end_frame(frame);
        self.record_span("present", present_started);

        // Everything this frame is timed by now, so it can be filed and the
        // chart can grow a column.
        self.ecs
            .world
            .resource_mut::<crate::ui::Profiler>()
            .end_frame();

        // The frame has been handled, so this frame's key presses are spent.
        {
            // A key pressed over the control port is let go at the end of the
            // frame it was pressed in: nothing is holding it down.
            if std::mem::take(&mut self.click_to_release) {
                self.ecs.world.resource_mut::<MouseInput>().left_down = false;
            }
            let mut keys = self.ecs.world.resource_mut::<Keys>();
            keys.end_frame();
            for code in self.keys_to_release.drain(..) {
                keys.release(code);
            }
        }

        Ok(())
    }
}

/// The size a headless run draws at when nothing says otherwise.
pub const DEFAULT_HEADLESS_SIZE: (u32, u32) = (1280, 800);

/// Reads `--headless` out of the command line.
///
/// Accepts a size — `--headless=1600x900` — since there is no window to take
/// one from. A size that cannot be read falls back to the default rather than
/// quietly opening a window, because the flag was asked for either way.
pub fn headless_from_args(args: impl IntoIterator<Item = String>) -> Option<(u32, u32)> {
    let flag = args
        .into_iter()
        .find(|arg| arg == "--headless" || arg.starts_with("--headless="))?;

    let Some((_, size)) = flag.split_once('=') else {
        return Some(DEFAULT_HEADLESS_SIZE);
    };
    match parse_size(size) {
        Some(size) => Some(size),
        None => {
            log::warn!("{flag:?} is not a size like 1280x800; using the default");
            Some(DEFAULT_HEADLESS_SIZE)
        }
    }
}

/// `1280x800` as a pair.
fn parse_size(text: &str) -> Option<(u32, u32)> {
    let (width, height) = text.split_once(['x', 'X'])?;
    let width: u32 = width.trim().parse().ok()?;
    let height: u32 = height.trim().parse().ok()?;
    (width > 0 && height > 0).then_some((width, height))
}

/// Runs the winit event loop, driving an [`AppState`] and the active [`Scene`].
///
/// ```no_run
/// # use codecraft::{App, AppState, scene::Scene};
/// # struct Splash;
/// # impl Scene for Splash {}
/// App::new("chessrs").scene(Splash).run();
/// ```
pub struct App {
    title: String,
    scene: Option<Box<dyn Scene>>,
    state: Option<AppState>,
    headless: Option<(u32, u32)>,
}

impl App {
    pub fn new(title: impl Into<String>) -> Self {
        let title_string = title.into();
        let title_local = title_string.clone();
        crate::logging::init(&title_string.clone());
        Self {
            title: title_local.into(),
            scene: None,
            state: None,
            headless: None,
        }
    }

    /// Runs with no window at all, drawing into an offscreen image.
    ///
    /// For driving the game from the control port while somebody else is
    /// using the desktop: nothing appears and nothing steals focus, and
    /// screenshots are read back off the GPU exactly as they are with a
    /// window.
    ///
    /// Setting this wins over the `--headless` argument, which is read for
    /// every app by [`App::run`].
    pub fn headless(mut self, size: (u32, u32)) -> Self {
        self.headless = Some(size);
        self
    }

    /// Sets the scene the app starts in.
    pub fn scene(mut self, scene: impl Scene) -> Self {
        self.scene = Some(Box::new(scene));
        self
    }

    pub fn run(mut self) {
        // Any app built on this renderer takes `--headless`, so a game does
        // not have to know the flag exists.
        let headless = self
            .headless
            .or_else(|| headless_from_args(std::env::args().skip(1)));
        if let Some((width, height)) = headless {
            self.run_headless(width, height);
            return;
        }
        let event_loop = EventLoop::new().expect("failed to create event loop");
        event_loop.set_control_flow(ControlFlow::Poll);
        event_loop.run_app(&mut self).expect("event loop error");
    }

    /// The frame loop, without winit.
    ///
    /// There is no vsync to pace it, so it is capped: a headless game running
    /// flat out would take a core from whoever is actually using the machine.
    fn run_headless(&mut self, width: u32, height: u32) {
        const FRAME: std::time::Duration = std::time::Duration::from_millis(16);

        let mut state = AppState::offscreen(width, height);
        log::info!("running headless at {width}x{height}");
        if let Some(scene) = self.scene.as_mut() {
            scene.setup(&mut state);
        }
        self.state = Some(state);
        self.apply_scene_change();

        loop {
            let started = std::time::Instant::now();
            let Some(state) = self.state.as_mut() else {
                return;
            };

            state.tick_time();
            state.take_control_requests();
            if state.should_quit() {
                log::info!("stopping");
                return;
            }
            if let Some(scene) = self.scene.as_mut() {
                scene.update(state);
            }
            self.apply_scene_change();

            let Some(state) = self.state.as_mut() else {
                return;
            };
            if let Err(error) = state.render() {
                log::warn!("frame failed: {error:?}");
            }
            self.apply_scene_change();

            if let Some(rest) = FRAME.checked_sub(started.elapsed()) {
                std::thread::sleep(rest);
            }
        }
    }

    /// Swaps in a scene queued via [`SceneCommands`]: clears the outgoing
    /// scene's entities, then sets the new one up.
    fn apply_scene_change(&mut self) {
        let Some(mut next) = self
            .state
            .as_mut()
            .and_then(|state| state.scenes.take_ready())
        else {
            return;
        };
        let Some(state) = self.state.as_mut() else {
            return;
        };
        state.clear_scene();
        next.setup(state);
        self.scene = Some(next);
    }
}

impl ApplicationHandler for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.state.is_some() {
            return;
        }
        let window = event_loop
            .create_window(Window::default_attributes().with_title(self.title.clone()))
            .expect("failed to create window");
        let mut state = AppState::new(Arc::new(window));
        if let Some(scene) = self.scene.as_mut() {
            scene.setup(&mut state);
        }
        state.request_redraw();
        self.state = Some(state);
        // The initial scene may have asked for a transition during setup.
        self.apply_scene_change();
    }

    fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
        // Scenes can transition on a timer, so keep frames coming rather than
        // only redrawing in response to input.
        if let Some(state) = self.state.as_ref() {
            state.request_redraw();
        }
    }

    fn window_event(
        &mut self,
        event_loop: &ActiveEventLoop,
        window_id: WindowId,
        event: WindowEvent,
    ) {
        let Some(state) = self.state.as_mut() else {
            return;
        };
        if state.window.as_ref().is_none_or(|w| window_id != w.id()) {
            return;
        }

        match event {
            WindowEvent::CloseRequested => event_loop.exit(),
            WindowEvent::Destroyed => event_loop.exit(),
            WindowEvent::Resized(size) => {
                state.resize(size.width, size.height);
                state.request_redraw();
            }
            WindowEvent::CursorMoved { position, .. } => {
                state.set_cursor(position.x as f32, position.y as f32);
                state.request_redraw();
            }
            WindowEvent::KeyboardInput {
                event:
                    KeyEvent {
                        physical_key: PhysicalKey::Code(code),
                        state: key_state,
                        repeat,
                        ..
                    },
                ..
            } => {
                state.set_key(code, key_state == ElementState::Pressed, repeat);
                state.request_redraw();
            }
            WindowEvent::MouseInput {
                state: ElementState::Pressed,
                button: MouseButton::Left,
                ..
            } => {
                state.set_mouse_left(true);
                state.request_redraw();
            }
            WindowEvent::MouseInput {
                state: ElementState::Released,
                button: MouseButton::Left,
                ..
            } => {
                state.set_mouse_left(false);
            }
            WindowEvent::MouseInput {
                state: button_state,
                button: MouseButton::Right,
                ..
            } => {
                state.set_mouse_right(button_state == ElementState::Pressed);
                state.request_redraw();
            }
            WindowEvent::MouseWheel { delta, .. } => {
                // A wheel reports clicks, a trackpad reports pixels; both
                // become clicks, at roughly the distance one notch scrolls.
                let clicks = match delta {
                    MouseScrollDelta::LineDelta(_, y) => y,
                    MouseScrollDelta::PixelDelta(position) => position.y as f32 / 60.0,
                };
                state.add_scroll(clicks);
                state.request_redraw();
            }
            WindowEvent::RedrawRequested => {
                state.tick_time();
                state.take_control_requests();
                if state.should_quit() {
                    event_loop.exit();
                    return;
                }
                if let Some(scene) = self.scene.as_mut() {
                    scene.update(state);
                }
                // A scene may transition from update; do it before rendering
                // so the new scene's UI is what gets drawn this frame.
                self.apply_scene_change();

                let Some(state) = self.state.as_mut() else {
                    return;
                };
                match state.render() {
                    Ok(()) => {}
                    Err(FrameError::Skip) => {}
                    Err(FrameError::Lost | FrameError::Outdated) => {
                        let size = state
                            .window
                            .as_ref()
                            .map(|w| w.inner_size())
                            .unwrap_or_default();
                        state.resize(size.width, size.height);
                    }
                    Err(e) => log::warn!("surface error: {e:?}"),
                }
                // Click handlers run inside render(); apply anything they queued.
                self.apply_scene_change();
            }
            _ => {}
        }
    }
}

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

    fn args(list: &[&str]) -> Vec<String> {
        list.iter().map(|arg| (*arg).to_string()).collect()
    }

    #[test]
    fn no_flag_means_a_window() {
        assert_eq!(headless_from_args(args(&[])), None);
        assert_eq!(headless_from_args(args(&["--debug", "board.glb"])), None);
        // Near misses are not the flag.
        assert_eq!(headless_from_args(args(&["--headlessly"])), None);
        assert_eq!(headless_from_args(args(&["headless"])), None);
    }

    #[test]
    fn the_bare_flag_takes_the_default_size() {
        assert_eq!(
            headless_from_args(args(&["--headless"])),
            Some(DEFAULT_HEADLESS_SIZE),
        );
        assert_eq!(
            headless_from_args(args(&["--foo", "--headless", "--bar"])),
            Some(DEFAULT_HEADLESS_SIZE),
        );
    }

    #[test]
    fn a_size_can_be_asked_for() {
        assert_eq!(
            headless_from_args(args(&["--headless=1600x900"])),
            Some((1600, 900)),
        );
        assert_eq!(
            headless_from_args(args(&["--headless=64X48"])),
            Some((64, 48))
        );
    }

    #[test]
    fn a_size_that_makes_no_sense_still_runs_headless() {
        // The flag was asked for; opening a window instead would be the one
        // thing the caller definitely did not want.
        for bad in [
            "--headless=",
            "--headless=wide",
            "--headless=1280",
            "--headless=0x800",
        ] {
            assert_eq!(
                headless_from_args(args(&[bad])),
                Some(DEFAULT_HEADLESS_SIZE),
                "{bad}",
            );
        }
    }
}