mirage-engine 0.1.0

Mirage, an immediate-mode 3D engine for simple games on desktop and the browser
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
//! What a session's ticks, saves and controls read back for its game.

use super::*;
use crate::{
    AxisBinding, InputAction, InputActions, InputAxisAction, InputButtonAction, NoInputAxes2,
    PointerDelta, WheelDelta,
};

/// The camera it draws from, which is not the default.
const WATCHED: Camera = Camera::new(
    View::look_at(Vec3::new(3.0, 4.0, 5.0), Vec3::X),
    Projection::orthographic(8.0),
);

meshes! { enum SphereSet { Sphere } }

/// One unlit red cube, squashed and moved left of the origin: drawn from
/// three meters back it covers pixels no other layout of its transform
/// would.
struct RedCube;

impl Game for RedCube {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(Camera::new(
            View::look_at(Vec3::new(0.0, 0.0, 3.0), Vec3::ZERO),
            Projection::perspective(60.0),
        ));
        ctx.draw(
            Cube.at(Transform::from_scale_rotation_translation(
                Vec3::new(1.0, 0.4, 1.0),
                Quat::IDENTITY,
                Vec3::new(-0.7, 0.0, 0.0),
            ))
            .material(Material::color(Color::rgb(1.0, 0.0, 0.0))),
        );
    }
}

/// One dim lit sphere seen from the direction its light comes from, at
/// whatever roughness the test set, or at the material's own where it
/// set none.
struct Sheen {
    roughness: Option<f32>,
}

impl Game for Sheen {
    type Meshes = SphereSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        ctx.set_camera(Camera::new(
            View::look_at(Vec3::Z * 2.0, Vec3::ZERO),
            Projection::orthographic(1.5),
        ));
        ctx.light(Light::directional(Vec3::NEG_Z, DIM));
        let material = Material::lit(DIM);
        ctx.draw(
            Sphere { subdivisions: 3 }.at(Vec3::ZERO).material(
                self.roughness
                    .map_or(material, |roughness| material.roughness(roughness)),
            ),
        );
    }
}

#[test]
fn a_surface_that_is_not_fully_rough_brightens_where_it_reflects_a_light_at_the_camera() {
    let sheen = |roughness| rendered(raw("headless roughness"), Sheen { roughness });
    let Some(plain) = sheen(None) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let (Some(fully_rough), Some(half_rough)) = (sheen(Some(1.0)), sheen(Some(0.5))) else {
        return;
    };
    // Five pixels off the middle of the sphere, whose normal turns away
    // from the light by that much of its radius.
    let turned = |pixels: &[u8]| i32::from(pixel(pixels, SIDE / 2 + 5, SIDE / 2)[0]);
    let reflected = |pixels: &[u8]| i32::from(middle(pixels)[0]);

    assert_eq!(
        fully_rough, plain,
        "a fully rough surface is what a material that names no roughness draws"
    );
    assert!(
        reflected(&half_rough) > reflected(&plain),
        "the highlight brightens the pixel the light reflects off towards the camera"
    );
    assert!(
        reflected(&half_rough) - reflected(&plain) > turned(&half_rough) - turned(&plain),
        "and brightens a pixel turned away from that angle less"
    );
}

/// Draws from a camera of its own, and keeps what each frame and tick
/// returns for the last drawn one.
#[derive(Default)]
struct Watcher {
    in_tick: Option<Camera>,
    in_frame: Option<Camera>,
}

impl Game for Watcher {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, ctx: &mut TickContext<'_, Self>) {
        self.in_tick = Some(ctx.last_camera());
    }

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.in_frame = Some(ctx.last_camera());
        ctx.set_camera(WATCHED);
    }
}

#[test]
fn a_frame_and_a_tick_are_answered_with_the_camera_the_last_frame_drew_from() {
    let Ok(mut session) = Session::new(
        Config::new("headless picking"),
        UVec2::splat(SIDE),
        |_ctx| Ok(Watcher::default()),
    ) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.step();
    assert_eq!(
        session.game().in_frame,
        Some(Camera::default()),
        "the first frame has none of its own to go on"
    );

    session.tick();
    session.step();

    assert_eq!(session.game().in_tick, Some(WATCHED));
    assert_eq!(session.game().in_frame, Some(WATCHED));
}

/// A game's one key, kept by hand: the derive names `::mirage_engine`, which
/// the engine's own tests are not.
#[derive(Clone, Copy)]
struct HighScore;

impl crate::Saves for HighScore {
    fn name(&self) -> &'static str {
        "Progress.HighScore"
    }
}

impl crate::SaveKey for HighScore {
    type Value = i64;

    fn fallback(&self) -> i64 {
        -1
    }
}

/// Saves one more than it read in its first tick, and reads what every
/// startup, tick and frame returns.
#[derive(Default)]
struct Keeper {
    at_startup: i64,
    in_tick: i64,
    in_frame: i64,
}

impl Game for Keeper {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, ctx: &mut TickContext<'_, Self>) {
        self.in_tick = ctx.saved(HighScore);
        ctx.save(HighScore, self.in_tick + 1);
    }

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.in_frame = ctx.saved(HighScore);
    }
}

#[test]
fn a_titleless_session_reads_fallbacks_and_reads_back_what_it_saved() {
    let Ok(mut session) = Session::new(
        Config::new("headless saves"),
        UVec2::splat(SIDE),
        |ctx: &mut InitContext<'_, Keeper>| {
            Ok(Keeper {
                at_startup: ctx.startup().saved(HighScore),
                ..Keeper::default()
            })
        },
    ) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.tick();
    session.step();
    session.tick();

    assert_eq!(session.game().at_startup, -1, "no run kept anything");
    assert_eq!(session.game().in_tick, 0, "the second tick reads the first");
    assert_eq!(session.game().in_frame, 0);
}

/// What one shared startup reads for a game of any vocabulary: the
/// target's size and what the last run kept.
fn shared_startup(startup: &mut Startup<'_>) -> (UVec2, i64) {
    (startup.window_size(), startup.saved(HighScore))
}

/// A game of another mesh vocabulary than [`Keeper`], keeping what
/// [`shared_startup`] read for it.
#[derive(Default)]
struct Shared {
    size: UVec2,
    score: i64,
}

impl Game for Shared {
    type Meshes = SphereSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, _: &mut FrameContext<'_, Self>) {}
}

#[test]
fn one_startup_helper_starts_two_games_of_different_vocabularies() {
    let started = Session::new(
        Config::new("headless shared startup"),
        UVec2::splat(SIDE),
        |ctx: &mut InitContext<'_, Shared>| {
            let (size, score) = shared_startup(ctx.startup());
            Ok(Shared { size, score })
        },
    );
    let Ok(shared) = started else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let Ok(keeper) = Session::new(
        Config::new("headless shared startup"),
        UVec2::splat(SIDE),
        |ctx: &mut InitContext<'_, Keeper>| {
            Ok(Keeper {
                at_startup: shared_startup(ctx.startup()).1,
                ..Keeper::default()
            })
        },
    ) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    assert_eq!(shared.game().size, UVec2::splat(SIDE));
    assert_eq!(
        keeper.game().at_startup,
        shared.game().score,
        "one helper read for both games"
    );
}

/// Adds up the time it is ticked, so its state depends only on the tick
/// count.
struct Walker {
    travelled: Duration,
    seen_elapsed: Duration,
}

impl Game for Walker {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, ctx: &mut TickContext<'_, Self>) {
        self.travelled += ctx.dt();
    }

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.seen_elapsed = ctx.elapsed();
    }
}

#[test]
fn ticks_are_fixed_and_only_ticks_advance_the_game() {
    let interval = Duration::from_millis(4);
    let config = Config::new("headless ticks").with_tick_interval(interval);
    let start = Walker {
        travelled: Duration::ZERO,
        seen_elapsed: Duration::ZERO,
    };
    let Ok(mut session) = Session::new(config, UVec2::splat(16), |_ctx| Ok(start)) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    for _ in 0..250 {
        session.tick();
    }
    session.step();

    assert_eq!(session.game().travelled, interval * 250);
    assert_eq!(session.game().seen_elapsed, interval * 250);

    session.step();
    assert_eq!(
        session.game().travelled,
        interval * 250,
        "rendering never ticks"
    );
}

/// Sets its own step to twice the start one on its first tick, and requests the end of the run
/// on its third; keeps every step it was given.
#[derive(Default)]
struct Pacer {
    steps: Vec<Duration>,
}

impl Game for Pacer {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, ctx: &mut TickContext<'_, Self>) {
        self.steps.push(ctx.dt());
        match self.steps.len() {
            1 => ctx.set_tick_interval(ctx.dt() * 2),
            3 => ctx.close(),
            _ => {}
        }
    }

    fn frame(&mut self, _ctx: &mut FrameContext<'_, Self>) {}
}

#[test]
fn a_tick_interval_set_in_a_tick_is_taken_from_the_next_tick_and_a_close_is_reported() {
    let interval = Duration::from_millis(4);
    let config = Config::new("headless pace").with_tick_interval(interval);
    let Ok(mut session) = Session::new(config, UVec2::splat(16), |_ctx| Ok(Pacer::default()))
    else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.tick();
    session.tick();
    assert_eq!(
        session.game().steps,
        vec![interval, interval * 2],
        "the tick that set it kept its own step"
    );
    assert!(!session.closed());

    session.tick();
    assert!(session.closed(), "the third tick requested it");
    session.step();
    session.tick();
    assert_eq!(
        session.game().steps.len(),
        4,
        "and the caller decides when to stop"
    );
    assert!(session.closed());
}

/// Counts the ticks and the frames that read a press of one key, and
/// the ticks that read its release; keeps what the last frame read of
/// that key, of the pointer, and of the control a capture returns.
#[derive(Default)]
struct Clicker {
    pressed_in_ticks: u32,
    released_in_ticks: u32,
    pressed_in_frames: u32,
    down: bool,
    pointer: Vec2,
    captured: Option<ButtonBinding>,
}

impl Game for Clicker {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = Key;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, ctx: &mut TickContext<'_, Self>) {
        self.pressed_in_ticks += u32::from(ctx.pressed(Key::Space));
        self.released_in_ticks += u32::from(ctx.released(Key::Space));
    }

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.pressed_in_frames += u32::from(ctx.pressed(Key::Space));
        self.down = ctx.down(Key::Space);
        self.pointer = ctx.pointer();
        self.captured = ctx.actuated_button();
    }
}

/// A session over a [`Clicker`], or `None` where the machine has no
/// usable graphics adapter.
fn clicking(title: &str) -> Option<Session<Clicker>> {
    Session::new(Config::new(title), UVec2::splat(SIDE), |_ctx| {
        Ok(Clicker::default())
    })
    .ok()
}

#[test]
fn a_session_reads_the_controls_it_is_handed_and_no_others() {
    let Some(mut session) = clicking("headless input") else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.tick();
    session.step();

    assert_eq!(session.game().pressed_in_ticks, 0, "nothing pressed one");
    assert_eq!(session.game().pressed_in_frames, 0);
    assert!(!session.game().down);
    assert_eq!(session.game().pointer, Vec2::ZERO, "and none moved it");

    session.set_pointer(Vec2::new(12.0, 20.0));
    session.step();

    assert_eq!(session.game().pointer, Vec2::new(12.0, 20.0));
}

#[test]
fn a_pressed_control_reaches_the_ticks_of_one_batch_and_the_frame_after_them() {
    let Some(mut session) = clicking("headless press") else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.press(Key::Space);
    session.tick();
    session.tick();
    session.step();

    assert_eq!(session.game().pressed_in_ticks, 1, "the ticks of one batch");
    assert_eq!(session.game().pressed_in_frames, 1, "and one frame");
    assert!(session.game().down);

    session.step();
    assert_eq!(session.game().pressed_in_frames, 1, "the edge is spent");
    assert!(session.game().down, "and the control is still held");

    session.release(Key::Space);
    session.tick();
    session.step();

    assert_eq!(session.game().released_in_ticks, 1, "as a release is");
    assert_eq!(session.game().pressed_in_ticks, 1, "and is no press");
    assert!(!session.game().down);
}

#[test]
fn a_pressed_mouse_button_is_the_control_a_capture_returns() {
    let Some(mut session) = clicking("headless click") else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.press(MouseButton::Left);
    session.step();

    assert_eq!(
        session.game().captured,
        Some(ButtonBinding::Mouse(MouseButton::Left))
    );

    session.step();
    assert_eq!(session.game().captured, None, "a held control is not new");
}

#[test]
fn a_step_batches_its_draws_and_places_them() {
    // A missing adapter and a broken driver both fail here; skip
    // either way.
    let Ok(mut session) = Session::new(raw("headless test"), UVec2::splat(64), |_ctx| Ok(RedCube))
    else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    let stats = session.step();
    assert_eq!((stats.draw_calls(), stats.instances()), (1, 1));

    let pixels = session.pixels().expect("the target reads back");
    assert_eq!(pixels.len(), 64 * 64 * 4);

    let pixel = |x: usize, y: usize| {
        let at = (y * 64 + x) * 4;
        [pixels[at], pixels[at + 1], pixels[at + 2], pixels[at + 3]]
    };
    // The far corner, which the squashed cube never reaches.
    let background = pixel(0, 0);

    assert_eq!(
        pixel(16, 32),
        [255, 0, 0, 255],
        "the cube sits left of center"
    );
    assert_eq!(pixel(32, 32), background, "the origin is empty");
    assert_eq!(pixel(16, 20), background, "the cube is squashed, not tall");
}

/// Sets the cursor it is given each frame, and none where it is given
/// none.
struct Pointing {
    cursor: Option<Cursor>,
}

impl Game for Pointing {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        if let Some(cursor) = self.cursor {
            ctx.set_cursor(cursor);
        }
    }
}

/// A session drawing `Pointing`, which starts out setting `first`.
fn pointing(first: Cursor) -> Option<Session<Pointing>> {
    started(Config::new("headless cursor"), UVec2::splat(SIDE), |_ctx| {
        Ok(Pointing {
            cursor: Some(first),
        })
    })
}

#[test]
fn a_frame_draws_the_pointer_as_the_cursor_it_set_and_as_the_arrow_where_it_set_none() {
    let Some(mut session) = pointing(Cursor::Grab) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    assert_eq!(session.cursor(), Cursor::Arrow, "before the first step");

    session.step();
    assert_eq!(session.cursor(), Cursor::Grab, "what the frame set");

    session.game_mut().cursor = None;
    session.step();
    assert_eq!(
        session.cursor(),
        Cursor::Arrow,
        "and a frame that sets none"
    );
}

#[test]
fn a_frame_that_holds_the_pointer_reads_back_held_until_a_frame_sets_another_cursor() {
    let Some(mut session) = pointing(Cursor::Held) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.step();
    assert_eq!(
        session.cursor(),
        Cursor::Held,
        "the frame holds the pointer"
    );

    session.game_mut().cursor = None;
    session.step();
    assert_eq!(
        session.cursor(),
        Cursor::Arrow,
        "and the frame after it releases it"
    );
}

/// The one action a pointer selects with, bound to the left mouse button.
#[derive(Clone, Copy)]
struct Select;

impl InputAction for Select {
    type Binding = ButtonBinding;

    fn defaults(&self) -> Vec<ButtonBinding> {
        self.bindings()
    }

    fn all() -> Vec<Self> {
        vec![Self]
    }

    fn name(&self) -> &'static str {
        "Select"
    }

    fn from_name(name: &str) -> Option<Self> {
        (name == "Select").then_some(Self)
    }
}

impl InputButtonAction for Select {
    fn bindings(&self) -> Vec<ButtonBinding> {
        vec![ButtonBinding::Mouse(MouseButton::Left)]
    }
}

/// The two actions a session drives: the wheel's upward lane zooms a
/// quarter apiece, and the pointer's sideways lane looks `0.01` per pixel.
#[derive(Clone, Copy)]
enum Steering {
    Zoom,
    Look,
}

impl InputAction for Steering {
    type Binding = AxisBinding;

    fn defaults(&self) -> Vec<AxisBinding> {
        self.bindings()
    }

    fn all() -> Vec<Self> {
        vec![Self::Zoom, Self::Look]
    }

    fn name(&self) -> &'static str {
        match self {
            Self::Zoom => "Zoom",
            Self::Look => "Look",
        }
    }

    fn from_name(name: &str) -> Option<Self> {
        match name {
            "Zoom" => Some(Self::Zoom),
            "Look" => Some(Self::Look),
            _ => None,
        }
    }
}

impl InputAxisAction for Steering {
    fn bindings(&self) -> Vec<AxisBinding> {
        match self {
            Self::Zoom => vec![AxisBinding::from(WheelDelta::Up).scale(0.25)],
            Self::Look => {
                vec![AxisBinding::pointer_delta(PointerDelta::Sideways).scale(0.01)]
            }
        }
    }
}

/// What a game driven by a pointer reads.
struct Controls;

impl InputActions for Controls {
    type Button = Select;
    type Axis = Steering;
    type Axis2 = NoInputAxes2;
}

/// Keeps what each frame read of the wheel, of the pointer and of the
/// button.
#[derive(Default)]
struct Zoomer {
    zoom: f32,
    look: f32,
    selected: bool,
}

impl Game for Zoomer {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = Controls;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.zoom = ctx.axis(Steering::Zoom);
        self.look = ctx.axis(Steering::Look);
        self.selected = ctx.pressed(Select);
    }
}

#[test]
fn a_wheel_the_session_turns_reads_back_through_an_axis_bound_to_its_lane() {
    let Some(mut session) = started(Config::new("headless wheel"), UVec2::splat(SIDE), |_ctx| {
        Ok(Zoomer::default())
    }) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.step();
    assert_eq!(session.game().zoom, 0.0, "nothing turned it");

    session.wheel_delta(WheelDelta::Up, 3.0);
    session.step();
    assert_eq!(session.game().zoom, 0.75, "three notches at a quarter each");

    session.step();
    assert_eq!(session.game().zoom, 0.0, "and a turn lasts one reading");

    session.wheel_delta(WheelDelta::Sideways, 3.0);
    session.step();
    assert_eq!(
        session.game().zoom,
        0.0,
        "and the other lane is another control"
    );
}

#[test]
fn a_pointer_the_session_moves_reads_back_the_whole_distance_its_scale_makes_of_it() {
    let Some(mut session) = started(
        Config::new("headless pointer"),
        UVec2::splat(SIDE),
        |_ctx| Ok(Zoomer::default()),
    ) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.step();
    assert_eq!(session.game().look, 0.0, "nothing moved it");

    session.pointer_delta(PointerDelta::Sideways, 500.0);
    session.step();
    assert_eq!(
        session.game().look,
        5.0,
        "five hundred pixels at a hundredth each"
    );

    session.step();
    assert_eq!(session.game().look, 0.0, "and a movement lasts one reading");
}

/// Keeps the step and the elapsed time of every frame it draws.
#[derive(Default)]
struct Timed {
    frames: Vec<(Duration, Duration)>,
}

impl Game for Timed {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = NoInputActions;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.frames.push((ctx.dt(), ctx.elapsed()));
    }
}

#[test]
fn a_frame_interval_paces_the_clock_every_step_reports() {
    let interval = Duration::from_micros(16_667);
    let config = Config::new("headless frames").with_tick_interval(interval);
    let Some(mut session) = started(config, UVec2::splat(SIDE), |_ctx| Ok(Timed::default())) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };

    session.step();
    assert_eq!(
        session.game().frames,
        vec![(Duration::ZERO, Duration::ZERO)],
        "a session starts at no interval at all"
    );

    let mut session = session.with_frame_interval(interval);
    session.step();
    session.step();

    assert_eq!(
        session.game().frames[1..],
        [(interval, Duration::ZERO), (interval, interval)],
        "every step covers the interval, and the clock adds it up"
    );

    session.tick();
    session.step();
    assert_eq!(
        session.game().frames[3],
        (interval, interval * 2),
        "a tick between two steps is the same span, counted once"
    );

    session.set_frame_interval(Duration::ZERO);
    session.step();
    assert_eq!(
        session.game().frames[4],
        (Duration::ZERO, interval * 3),
        "and a step of no interval leaves the clock where it is"
    );
}

#[test]
fn ticks_and_steps_over_one_span_advance_the_clock_once() {
    let interval = Duration::from_micros(16_667);
    let config = Config::new("headless clock").with_tick_interval(interval);
    let Some(session) = started(config, UVec2::splat(SIDE), |_ctx| Ok(Timed::default())) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    let mut session = session.with_frame_interval(interval);

    for _ in 0..3 {
        session.tick();
        session.step();
    }

    let elapsed: Vec<Duration> = session.game().frames.iter().map(|&(_, at)| at).collect();
    assert_eq!(
        elapsed,
        vec![interval, interval * 2, interval * 3],
        "a tick and a step over one span count it once"
    );
}

/// Keeps what every frame read of the clicks one action has taken.
#[derive(Default)]
struct Counter {
    clicks: Vec<u32>,
}

impl Game for Counter {
    type Meshes = CubeSet;
    type Sounds = NoSounds;
    type InputActions = Controls;
    type Skyboxes = NoSkyboxes;
    type SurfaceStyles = ();
    type PostEffects = ();

    fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

    fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
        self.clicks.push(ctx.clicks(Select));
    }
}

/// One click of the session's own mouse, and the clicks in a row the frame
/// that read its press counted it as.
fn clicked(session: &mut Session<Counter>) -> u32 {
    session.press(MouseButton::Left);
    session.step();
    let clicks = *session
        .game()
        .clicks
        .last()
        .expect("a frame read the press");

    session.release(MouseButton::Left);
    session.step();
    clicks
}

#[test]
fn presses_in_a_row_read_back_as_the_clicks_of_one_action() {
    let config =
        Config::new("headless clicks").with_double_click_interval(Duration::from_millis(400));
    let Some(session) = started(config, UVec2::splat(SIDE), |_ctx| Ok(Counter::default())) else {
        eprintln!("skipped: this machine has no usable graphics adapter");
        return;
    };
    // Every step covers 100 milliseconds, so a click takes two of them.
    let mut session = session.with_frame_interval(Duration::from_millis(100));

    session.step();
    assert_eq!(session.game().clicks, vec![0], "a frame with no press");

    assert_eq!(clicked(&mut session), 1, "the first click");
    assert_eq!(clicked(&mut session), 2, "a second within the interval");

    for _ in 0..5 {
        session.step();
    }
    assert_eq!(clicked(&mut session), 1, "and one 300 milliseconds past it");
}

#[cfg(feature = "ui")]
mod ui {
    use super::*;

    /// Sets one cursor every frame, under one `ui.link` in the layer's top
    /// left.
    struct Linked;

    impl Game for Linked {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

        fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            ctx.set_cursor(Cursor::Grab);
            ctx.ui(|ui| {
                let _ = ui.link("controls");
            });
        }
    }

    #[test]
    fn the_ui_draws_its_own_cursor_where_the_pointer_is_over_what_it_drew() {
        let shown = |at| -> Option<Cursor> {
            let mut session = started(
                Config::new("headless ui cursor"),
                UVec2::splat(64),
                |_ctx| Ok(Linked),
            )?;

            session.step();
            session.set_pointer(at);
            session.step();
            Some(session.cursor())
        };

        let Some(over) = shown(Vec2::new(12.0, 12.0)) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };
        let Some(clear_of_it) = shown(Vec2::new(40.0, 40.0)) else {
            return;
        };

        assert_eq!(over, Cursor::Pointer, "the link draws the hand");
        assert_eq!(clear_of_it, Cursor::Grab, "and the frame's own clear of it");
    }

    /// Holds the pointer every frame, under one `ui.link` in the layer's
    /// top left.
    struct HeldUnderALink;

    impl Game for HeldUnderALink {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

        fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            ctx.set_cursor(Cursor::Held);
            ctx.ui(|ui| {
                let _ = ui.link("controls");
            });
        }
    }

    #[test]
    fn a_held_pointer_stays_held_over_what_the_ui_draws_a_cursor_of_its_own_for() {
        let Some(mut session) = started(
            Config::new("headless ui held pointer"),
            UVec2::splat(64),
            |_ctx| Ok(HeldUnderALink),
        ) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };

        session.step();
        session.set_pointer(Vec2::new(12.0, 12.0));
        session.step();

        assert_eq!(session.cursor(), Cursor::Held);
    }

    /// One line of UI text in the layer's top left, and what the UI claimed
    /// of the pointer before the frame reading it ran.
    #[derive(Default)]
    struct Hud {
        claimed: bool,
    }

    impl Game for Hud {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

        fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            self.claimed = ctx.ui_wants_pointer();
            ctx.ui(|ui| {
                ui.label("hp");
            });
        }
    }

    #[test]
    fn a_pointer_the_session_places_claims_the_pointer_over_what_the_ui_drew() {
        let claimed = |at| -> Option<bool> {
            let mut session = started(
                Config::new("headless ui pointer"),
                UVec2::splat(64),
                |_ctx| Ok(Hud::default()),
            )?;

            session.step();
            session.set_pointer(at);
            session.step();
            session.step();
            Some(session.game().claimed)
        };

        let Some(over) = claimed(Vec2::new(12.0, 12.0)) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };
        let Some(clear_of_it) = claimed(Vec2::new(40.0, 40.0)) else {
            return;
        };

        assert!(over, "a pointer placed over the text is claimed");
        assert!(!clear_of_it, "and one placed clear of it is not");
    }

    /// One UI text entry holding what was typed into it, which keeps the
    /// keyboard every frame.
    #[derive(Default)]
    struct Entry {
        typed: String,
    }

    impl Game for Entry {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

        fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            let typed = &mut self.typed;
            ctx.ui(|ui| {
                ui.text_edit_singleline(typed).request_focus();
            });
        }
    }

    #[test]
    fn text_the_session_types_reaches_the_entry_holding_the_keyboard() {
        let Some(mut session) =
            started(Config::new("headless ui text"), UVec2::splat(64), |_ctx| {
                Ok(Entry::default())
            })
        else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };

        session.step();
        session.type_text("ab");
        session.step();
        assert_eq!(session.game().typed, "ab", "the text reaches the entry");

        session.press(Key::Backspace);
        session.step();
        assert_eq!(session.game().typed, "a", "and a press takes a letter off");
    }

    /// One UI button in the layer's top left, and what each frame read of
    /// the click, of the action bound to the same button, and of the claim
    /// the frame before.
    #[derive(Default)]
    struct Panel {
        clicks: u32,
        presses: u32,
        claimed: bool,
    }

    impl Game for Panel {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = Controls;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

        fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            self.presses += u32::from(ctx.pressed(Select));
            self.claimed = ctx.ui_wants_pointer();

            let clicked = &mut self.clicks;
            ctx.ui(|ui| {
                *clicked += u32::from(ui.button("go").clicked());
            });
        }
    }

    #[test]
    fn one_press_reaches_the_game_and_the_ui_button_under_the_pointer() {
        let Some(mut session) = started(
            Config::new("headless ui click"),
            UVec2::new(128, 64),
            |_ctx| Ok(Panel::default()),
        ) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };

        session.step();
        session.set_pointer(Vec2::new(20.0, 16.0));
        session.press(MouseButton::Left);
        session.step();

        assert_eq!(session.game().presses, 1, "the game reads the press");

        session.release(MouseButton::Left);
        session.step();

        assert_eq!(session.game().clicks, 1, "and the button reads the click");
        assert_eq!(session.game().presses, 1, "off one press");

        session.step();
        assert!(
            session.game().claimed,
            "which the UI claimed the pointer for"
        );
    }

    /// One UI button in the layer's top left, drawn at a zoom of its own;
    /// what the UI claimed of the pointer the frame before, and how wide
    /// the layer was in points.
    struct Zoomed {
        zoom: f32,
        claimed: bool,
        width: f32,
    }

    impl Game for Zoomed {
        type Meshes = CubeSet;
        type Sounds = NoSounds;
        type InputActions = NoInputActions;
        type Skyboxes = NoSkyboxes;
        type SurfaceStyles = ();
        type PostEffects = ();

        fn tick(&mut self, _ctx: &mut TickContext<'_, Self>) {}

        fn frame(&mut self, ctx: &mut FrameContext<'_, Self>) {
            self.claimed = ctx.ui_wants_pointer();

            let zoom = self.zoom;
            let width = &mut self.width;
            ctx.ui(|ui| {
                ui.ctx().set_zoom_factor(zoom);
                *width = ui.max_rect().width();
                let _ = ui.button("go");
            });
        }
    }

    #[test]
    fn a_pointer_is_placed_in_the_points_the_layer_lays_out_at() {
        // The button covers the layer's top left corner, some thirty points
        // across: at a zoom of two the pointer below lands on it in points,
        // and at a zoom of one it lands well clear of it.
        let laid_out = |zoom| -> Option<(bool, f32)> {
            let mut session = started(
                Config::new("headless ui zoom"),
                UVec2::new(128, 64),
                |_ctx| {
                    Ok(Zoomed {
                        zoom,
                        claimed: false,
                        width: 0.0,
                    })
                },
            )?;

            session.step();
            session.step();
            session.set_pointer(Vec2::new(60.0, 30.0));
            session.step();
            session.step();
            Some((session.game().claimed, session.game().width))
        };

        let Some((zoomed, width)) = laid_out(2.0) else {
            eprintln!("skipped: this machine has no usable graphics adapter");
            return;
        };
        let Some((plain, whole_width)) = laid_out(1.0) else {
            return;
        };

        assert!(
            zoomed,
            "the pointer divides by the scale the layer lays out at"
        );
        assert!(
            !plain,
            "where at a scale of one it is the pixel it was given"
        );
        assert_eq!(
            width, 48.0,
            "and the layer covers the target, not twice it: 128 pixels at two \
             a point, less the margin on either side"
        );
        assert_eq!(
            whole_width, 112.0,
            "where at a scale of one it is those 128 less the margin"
        );
    }
}