mirage-engine 0.2.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
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
//! Every control's reading this frame, the frame before, and the last frame
//! whose ticks ran. A binding resolves against a reading; an edge is
//! measured between two of them.

use core::time::Duration;

use winit::event::{DeviceEvent, MouseScrollDelta, TouchPhase, WindowEvent};
use winit::keyboard::PhysicalKey;

use crate::input::binding::{
    Axis2Binding, Axis2Source, AxisBinding, AxisSource, ButtonBinding, JoystickControl, Key,
    MouseButton, Pad, PadAxis, PointerDelta, Stick, WheelDelta,
};
use crate::input::pad::Pads;
use crate::math::Vec2;
use crate::platform::WHEEL_RATE;

/// Controls with no standard layout one reading keeps, over every device it
/// read them from.
const UNMAPPED: usize = 64;

/// Level an unmapped control must read at to count as held.
const HELD: f32 = 0.5;

/// Distance a control moves before capture takes it for the one the player
/// meant.
const ACTUATED: f32 = AxisBinding::DEFAULT_DEADZONE;

/// How far a window reports the wheel turning for one notch, in lines and
/// in pixels. Each platform seam states the rate its own windows count by.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct WheelRate {
    lines: f32,
    pixels: f32,
}

impl WheelRate {
    /// What a desktop window counts a notch as: one line, which every
    /// desktop backend reports for one step of a wheel, and 100 pixels,
    /// the rate a browser counts by, so a device that reports pixels reads
    /// the same on both targets.
    pub(crate) const DESKTOP: Self = Self::per_notch(1.0, 100.0);

    /// One notch as a browser window reports it: three lines when the
    /// browser counts in lines, and 100 pixels when it counts in pixels.
    pub(crate) const BROWSER: Self = Self::per_notch(3.0, 100.0);

    const fn per_notch(lines: f32, pixels: f32) -> Self {
        Self { lines, pixels }
    }

    /// `delta` as the notches the wheel turned, counted right and away. A
    /// window counts its sideways lane the other way round, and counts in
    /// lines or in pixels by the device that turned it.
    fn notches(self, delta: MouseScrollDelta) -> Vec2 {
        let (sideways, up, rate) = match delta {
            MouseScrollDelta::LineDelta(x, y) => (x, y, self.lines),
            MouseScrollDelta::PixelDelta(pixels) => (pixels.x as f32, pixels.y as f32, self.pixels),
        };
        Vec2::new(-sideways, up) / rate
    }

    /// `turn` as the lines a window reports for it, counted the window's
    /// own way: what the UI reads behind a window.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn lines(self, turn: Vec2) -> Vec2 {
        Vec2::new(-turn.x, turn.y) * self.lines
    }
}

/// The controls as one [`Devices::sample`] closed them: plain data that
/// crosses from the devices to the game, which reads one frame's queries
/// from it and folds it into what its ticks read.
#[derive(Clone, Copy, Default)]
pub(crate) struct Controls {
    frame: Snapshot,
    /// The keys and mouse buttons that went down since the last sample, so
    /// that a tap made while no ticks ran is still held for the ticks that
    /// follow.
    tapped: Pressed,
    clicking: Clicking,
}

impl Controls {
    /// This frame's reading against the frame before.
    pub(crate) fn frame(&self) -> &Snapshot {
        &self.frame
    }

    /// How many presses in a row the last press made: `1` for a press on
    /// its own, and `0` where the count is on no control of `bindings`.
    pub(crate) fn clicks(&self, bindings: &[ButtonBinding]) -> u32 {
        self.clicking.clicks(bindings)
    }
}

/// What the ticks read, measured on the game thread alone: this frame's
/// reading against the last frame whose ticks ran, and the taps since.
#[derive(Default)]
pub(crate) struct Ticks {
    snapshot: Snapshot,
    tapped: Pressed,
}

impl Ticks {
    /// Folds `controls` in: the ticks read its frame, with every tap since
    /// they last ran held down in it.
    pub(crate) fn fold(&mut self, controls: &Controls) {
        self.tapped.merge(controls.tapped);
        self.snapshot.now = controls.frame.now.holding(self.tapped);
    }

    /// This frame's reading against the last frame whose ticks ran.
    pub(crate) fn snapshot(&self) -> &Snapshot {
        &self.snapshot
    }

    /// Ends the ticks of one frame: the edges they read are spent, so no
    /// later tick reads them, and the taps they held are cleared.
    pub(crate) fn ticked(&mut self) {
        self.snapshot.before = self.snapshot.now;
        self.tapped = Pressed::default();
    }
}

/// Two readings and the edge between them: this frame against the frame
/// before, or this frame against the last frame whose ticks ran.
#[derive(Clone, Copy, Default)]
pub(crate) struct Snapshot {
    now: Reading,
    before: Reading,
}

impl Snapshot {
    pub(crate) fn down(&self, bindings: &[ButtonBinding]) -> bool {
        self.now.any(bindings)
    }

    pub(crate) fn pressed(&self, bindings: &[ButtonBinding]) -> bool {
        self.now.any(bindings) && !self.before.any(bindings)
    }

    pub(crate) fn released(&self, bindings: &[ButtonBinding]) -> bool {
        !self.now.any(bindings) && self.before.any(bindings)
    }

    /// Reading of the binding pushed furthest, so that alternatives never
    /// add up.
    pub(crate) fn axis(&self, bindings: &[AxisBinding]) -> f32 {
        bindings.iter().fold(0.0, |most, binding| {
            let value = self.now.axis(binding);
            match value.abs() > most.abs() {
                true => value,
                false => most,
            }
        })
    }

    pub(crate) fn axis2(&self, bindings: &[Axis2Binding]) -> Vec2 {
        bindings.iter().fold(Vec2::ZERO, |most, binding| {
            let value = self.now.axis2(binding);
            match value.length_squared() > most.length_squared() {
                true => value,
                false => most,
            }
        })
    }

    pub(crate) fn pointer(&self) -> Vec2 {
        self.now.pointer
    }

    /// The button control the player pressed this frame, out of every device
    /// there is.
    pub(crate) fn actuated_button(&self) -> Option<ButtonBinding> {
        let keys = Key::ALL.iter().copied().map(ButtonBinding::Key);
        let mouse = MouseButton::ALL.iter().copied().map(ButtonBinding::Mouse);
        let pad = Pad::ALL.iter().copied().map(ButtonBinding::Pad);
        let joystick = self
            .now
            .joystick
            .iter()
            .map(|(control, _)| ButtonBinding::Joystick(control));

        keys.chain(mouse)
            .chain(pad)
            .chain(joystick)
            .find(|&binding| self.now.held(binding) && !self.before.held(binding))
    }

    /// The analog control the player pushed this frame, at the knobs a
    /// binding starts with; a pointer or wheel is never captured, because the
    /// smallest nudge would take it.
    pub(crate) fn actuated_axis(&self) -> Option<AxisBinding> {
        let pad = PadAxis::ALL.iter().copied().map(AxisBinding::pad);
        let joystick = self
            .now
            .joystick_axes
            .iter()
            .map(|(control, _)| AxisBinding::joystick(control));

        pad.chain(joystick).find(|binding| {
            self.now.axis(binding).abs() > ACTUATED && self.before.axis(binding).abs() <= ACTUATED
        })
    }

    /// The stick the player pushed this frame, at the knobs a binding starts
    /// with; the pointer and the wheel are never captured, as for an axis.
    pub(crate) fn actuated_axis2(&self) -> Option<Axis2Binding> {
        Stick::ALL
            .iter()
            .copied()
            .map(Axis2Binding::stick)
            .find(|binding| {
                self.now.axis2(binding).length() > ACTUATED
                    && self.before.axis2(binding).length() <= ACTUATED
            })
    }
}

/// The presses one control has taken in a row: which control, when the
/// last of them landed on the run's own clock, and how many landed each
/// within one double click interval of the one before it.
#[derive(Clone, Copy, Default)]
struct Clicking {
    control: Option<ButtonBinding>,
    at: Duration,
    count: u32,
}

impl Clicking {
    /// Counts `pressed` at `at`: the same control again within `within` of
    /// the last press counts on from it, and anything else starts the count
    /// again.
    fn press(&mut self, pressed: Option<ButtonBinding>, at: Duration, within: Duration) {
        let Some(control) = pressed else {
            return;
        };
        let again = self.control == Some(control) && at.saturating_sub(self.at) <= within;

        self.count = match again {
            true => self.count + 1,
            false => 1,
        };
        self.control = Some(control);
        self.at = at;
    }

    /// The presses in a row, where the last of them was one of `bindings`,
    /// and `0` where the count is on another control.
    fn clicks(&self, bindings: &[ButtonBinding]) -> u32 {
        match self
            .control
            .is_some_and(|control| bindings.contains(&control))
        {
            true => self.count,
            false => 0,
        }
    }
}

/// Every control's reading at one instant.
#[derive(Clone, Copy)]
pub(crate) struct Reading {
    pressed: Pressed,
    pad: [bool; Pad::COUNT],
    pad_axes: [f32; PadAxis::COUNT],
    joystick: Unmapped,
    joystick_axes: Unmapped,
    pointer: Vec2,
    /// Distance the pointer moved since the last snapshot, counted right
    /// and up.
    pointer_delta: Vec2,
    /// Notches the wheel turned since the last snapshot, counted right and
    /// away.
    wheel: Vec2,
}

impl Reading {
    /// This reading with `tapped` held down in it, so that a control
    /// pressed and released between two readings is down in one of them.
    fn holding(mut self, tapped: Pressed) -> Self {
        self.pressed.merge(tapped);
        self
    }

    /// Presses a button of the standard gamepad layout; every device feeds
    /// one player, so any of them holding it is enough.
    pub(crate) fn press_pad(&mut self, button: Pad) {
        self.pad[button.index()] = true;
    }

    /// Pushes a lane of the standard gamepad layout; the device pushing it
    /// furthest is the one that counts.
    pub(crate) fn push_pad(&mut self, axis: PadAxis, value: f32) {
        let lane = &mut self.pad_axes[axis.index()];
        if value.abs() > lane.abs() {
            *lane = value.clamp(-1.0, 1.0);
        }
    }

    /// Presses a button of a device with no standard layout, by the number
    /// its platform reports for it.
    pub(crate) fn press_joystick(&mut self, control: JoystickControl) {
        self.joystick.push(control, 1.0);
    }

    /// Pushes an axis of a device with no standard layout.
    pub(crate) fn push_joystick(&mut self, control: JoystickControl, value: f32) {
        self.joystick_axes.push(control, value.clamp(-1.0, 1.0));
    }

    /// Drops what the pads read last frame, which are polled rather than
    /// evented and so are read whole each time.
    fn forget_pads(&mut self) {
        self.pad = [false; Pad::COUNT];
        self.pad_axes = [0.0; PadAxis::COUNT];
        self.joystick = Unmapped::default();
        self.joystick_axes = Unmapped::default();
    }

    fn any(&self, bindings: &[ButtonBinding]) -> bool {
        bindings.iter().any(|&binding| self.held(binding))
    }

    fn held(&self, binding: ButtonBinding) -> bool {
        match binding {
            ButtonBinding::Key(key) => self.pressed.keys[key.index()],
            ButtonBinding::Mouse(button) => self.pressed.mouse[button.index()],
            ButtonBinding::Pad(button) => self.pad[button.index()],
            ButtonBinding::Joystick(control) => self.joystick.value(control) > HELD,
        }
    }

    fn axis(&self, binding: &AxisBinding) -> f32 {
        let raw = match binding.source {
            AxisSource::Pad(axis) => self.pad_axes[axis.index()],
            AxisSource::Joystick(control) => self.joystick_axes.value(control),
            AxisSource::Pointer(lane) => match lane {
                PointerDelta::Sideways => self.pointer_delta.x,
                PointerDelta::Up => self.pointer_delta.y,
            },
            AxisSource::Wheel(lane) => match lane {
                WheelDelta::Sideways => self.wheel.x,
                WheelDelta::Up => self.wheel.y,
            },
            AxisSource::Buttons { negative, positive } => {
                weigh(self.held(positive)) - weigh(self.held(negative))
            }
        };
        binding.resolve(raw)
    }

    fn axis2(&self, binding: &Axis2Binding) -> Vec2 {
        let raw = match binding.source {
            Axis2Source::Stick(stick) => {
                let (x, y) = stick.lanes();
                Vec2::new(self.pad_axes[x.index()], self.pad_axes[y.index()])
            }
            Axis2Source::Pointer => self.pointer_delta,
            Axis2Source::Wheel => self.wheel,
            Axis2Source::Buttons {
                left,
                right,
                down,
                up,
            } => Vec2::new(
                weigh(self.held(right)) - weigh(self.held(left)),
                weigh(self.held(up)) - weigh(self.held(down)),
            ),
        };
        binding.resolve(raw)
    }
}

impl Default for Reading {
    fn default() -> Self {
        Self {
            pressed: Pressed::default(),
            pad: [false; Pad::COUNT],
            pad_axes: [0.0; PadAxis::COUNT],
            joystick: Unmapped::default(),
            joystick_axes: Unmapped::default(),
            pointer: Vec2::ZERO,
            pointer_delta: Vec2::ZERO,
            wheel: Vec2::ZERO,
        }
    }
}

/// The keys and mouse buttons the window's events report as down.
#[derive(Clone, Copy)]
struct Pressed {
    keys: [bool; Key::COUNT],
    mouse: [bool; MouseButton::COUNT],
}

impl Pressed {
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    fn held(&self, control: Switch) -> bool {
        match control {
            Switch::Key(key) => self.keys[key.index()],
            Switch::Mouse(button) => self.mouse[button.index()],
        }
    }

    fn at(&mut self, control: Switch) -> &mut bool {
        match control {
            Switch::Key(key) => &mut self.keys[key.index()],
            Switch::Mouse(button) => &mut self.mouse[button.index()],
        }
    }

    fn merge(&mut self, other: Self) {
        for (held, tapped) in self.keys.iter_mut().zip(other.keys) {
            *held |= tapped;
        }
        for (held, tapped) in self.mouse.iter_mut().zip(other.mouse) {
            *held |= tapped;
        }
    }
}

impl Default for Pressed {
    fn default() -> Self {
        Self {
            keys: [false; Key::COUNT],
            mouse: [false; MouseButton::COUNT],
        }
    }
}

/// A control the window sends events for, rather than one that is polled.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Switch {
    /// A key, by physical position.
    Key(Key),
    /// A mouse button, which the first touch of a touch screen also presses.
    Mouse(MouseButton),
}

impl From<Key> for Switch {
    fn from(key: Key) -> Self {
        Self::Key(key)
    }
}

impl From<MouseButton> for Switch {
    fn from(button: MouseButton) -> Self {
        Self::Mouse(button)
    }
}

/// The controls of devices with no standard layout, by the number their
/// platform reports for them, kept in that order so that capture is repeatable.
#[derive(Clone, Copy)]
struct Unmapped {
    controls: [(JoystickControl, f32); UNMAPPED],
    len: usize,
}

impl Unmapped {
    /// Keeps the strongest reading for `control`, so that many devices
    /// merge into the one player they all feed.
    fn push(&mut self, control: JoystickControl, value: f32) {
        match self.controls[..self.len].binary_search_by_key(&control, |&(id, _)| id) {
            Ok(at) if value.abs() > self.controls[at].1.abs() => self.controls[at].1 = value,
            Ok(_) => {}
            Err(at) if self.len < UNMAPPED => {
                self.controls[at..=self.len].rotate_right(1);
                self.controls[at] = (control, value);
                self.len += 1;
            }
            Err(_) => {}
        }
    }

    fn value(&self, control: JoystickControl) -> f32 {
        match self.controls[..self.len].binary_search_by_key(&control, |&(id, _)| id) {
            Ok(at) => self.controls[at].1,
            Err(_) => 0.0,
        }
    }

    fn iter(&self) -> impl Iterator<Item = (JoystickControl, f32)> + '_ {
        self.controls[..self.len].iter().copied()
    }
}

impl Default for Unmapped {
    fn default() -> Self {
        Self {
            controls: [(JoystickControl::new(0), 0.0); UNMAPPED],
            len: 0,
        }
    }
}

/// Turns the window's events and the pads' readings into one [`Controls`]
/// per drawn frame.
pub(crate) struct Devices {
    pads: Pads,
    /// How long after a press a second one still counts as a double click.
    double_click: Duration,
    live: Reading,
    /// The keys and mouse buttons that went down since the last sample, so
    /// that a tap between two frames is still held for one of them.
    tapped: Pressed,
    /// Position the pointer was last seen at, which is what its movement
    /// is measured from.
    tracked: Option<Vec2>,
    /// Whether the window holds the pointer in place, which leaves the
    /// device's own movement the one thing that moves it.
    held: bool,
    /// The touch used as the pointer, out of however many the screen
    /// reports.
    touch: Option<u64>,
    /// The reading the last sample closed with, which the next one measures
    /// its edges from.
    before: Reading,
    clicking: Clicking,
}

impl Devices {
    /// Devices reading nothing yet, with `pads` polled at every sample and a
    /// press within `double_click` of the last one counted as one more click.
    pub(crate) fn new(pads: Pads, double_click: Duration) -> Self {
        Self {
            pads,
            double_click,
            live: Reading::default(),
            tapped: Pressed::default(),
            tracked: None,
            held: false,
            touch: None,
            before: Reading::default(),
            clicking: Clicking::default(),
        }
    }

    /// Takes what `event` reports about the controls; the engine never keeps
    /// it from the game because the UI claimed it.
    pub(crate) fn see(&mut self, event: &WindowEvent) {
        match event {
            WindowEvent::KeyboardInput { event, .. } => {
                let PhysicalKey::Code(code) = event.physical_key else {
                    return;
                };
                let Some(key) = Key::from_code(code) else {
                    return;
                };
                self.press(Switch::Key(key), event.state.is_pressed());
            }
            WindowEvent::MouseInput { button, state, .. } => {
                let Some(button) = MouseButton::from_winit(*button) else {
                    return;
                };
                self.press(Switch::Mouse(button), state.is_pressed());
            }
            WindowEvent::CursorMoved { position, .. } => {
                self.point_at(Vec2::new(position.x as f32, position.y as f32));
            }
            WindowEvent::MouseWheel { delta, .. } => {
                self.live.wheel += WHEEL_RATE.notches(*delta);
            }
            WindowEvent::Touch(touch) => self.touch(touch),
            WindowEvent::Focused(false) => {
                self.live.pressed = Pressed::default();
                self.touch = None;
                self.hold_pointer(false);
            }
            _ => {}
        }
    }

    /// Takes the movement `event` reports of a device itself, which is the
    /// one thing a held pointer moves by; the window reports no place for
    /// one.
    pub(crate) fn see_device(&mut self, event: &DeviceEvent) {
        let DeviceEvent::MouseMotion { delta: (x, y) } = event else {
            return;
        };
        if self.held {
            self.move_pointer(Vec2::new(*x as f32, -(*y as f32)));
        }
    }

    /// Holds the pointer in place, so that it moves by what the device
    /// reports alone, or releases it.
    ///
    /// A released pointer measures its next movement from wherever the
    /// window reports it next, however far the hold left it from there. A
    /// window loses its hold as it loses focus.
    pub(crate) fn hold_pointer(&mut self, held: bool) {
        if core::mem::replace(&mut self.held, held) != held && !held {
            self.tracked = None;
        }
    }

    /// Ends the events of one frame and starts the next: reads the pads,
    /// closes this frame's controls at `at` on its driver's clock, counts a
    /// press landing within the double click interval of the last one as
    /// one more click — the first press edge in the order keys, mouse, pad,
    /// joystick where a frame holds more than one — and clears what only
    /// lasts a frame.
    pub(crate) fn sample(&mut self, at: Duration) -> Controls {
        self.live.forget_pads();
        self.pads.poll(&mut self.live);

        let tapped = core::mem::take(&mut self.tapped);
        let now = self.live.holding(tapped);
        let frame = Snapshot {
            before: core::mem::replace(&mut self.before, now),
            now,
        };
        self.clicking
            .press(frame.actuated_button(), at, self.double_click);

        self.live.pointer_delta = Vec2::ZERO;
        self.live.wheel = Vec2::ZERO;
        Controls {
            frame,
            tapped,
            clicking: self.clicking,
        }
    }

    pub(crate) fn press(&mut self, control: Switch, down: bool) {
        *self.live.pressed.at(control) = down;
        if down {
            *self.tapped.at(control) = true;
        }
    }

    /// Moves the pointer by `pixels`, counted right and up, and places it
    /// nowhere: what a held pointer and a session both move by.
    pub(crate) fn move_pointer(&mut self, pixels: Vec2) {
        self.live.pointer_delta += pixels;
    }

    /// Turns the wheel by `notches`, counted right and away, in place of a
    /// window's event; only a session calls this.
    #[cfg(feature = "offscreen")]
    pub(crate) fn turn_wheel(&mut self, notches: Vec2) {
        self.live.wheel += notches;
    }

    /// Whether `control` is held as of now, before any snapshot closes;
    /// only a session reads this, for the keys it passes to the UI.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn holds(&self, control: Switch) -> bool {
        self.live.pressed.held(control)
    }

    /// The `Shift`, `Control` and `Alt` keys held as of now, before any
    /// snapshot closes, as the UI reads them, with `Control` as its command
    /// key.
    ///
    /// A window on `macOS` takes its command key from `Super`, which [`Key`]
    /// has no position for, so a session's `Control` is what a command reads
    /// there.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn modifiers(&self) -> egui::Modifiers {
        let either = |left, right| self.holds(Switch::Key(left)) || self.holds(Switch::Key(right));
        let ctrl = either(Key::LeftControl, Key::RightControl);

        egui::Modifiers {
            alt: either(Key::LeftAlt, Key::RightAlt),
            ctrl,
            shift: either(Key::LeftShift, Key::RightShift),
            mac_cmd: false,
            command: ctrl,
        }
    }

    /// Where the pointer has been placed, which is where a session's next
    /// press lands, or `None` where nothing has placed it yet; only a
    /// session reads this.
    #[cfg(all(feature = "ui", feature = "offscreen"))]
    pub(crate) fn pointing_at(&self) -> Option<Vec2> {
        self.tracked
    }

    /// Places the pointer at `position` and counts how far it moved to get
    /// there; a held pointer stays where it is instead.
    pub(crate) fn point_at(&mut self, position: Vec2) {
        if self.held {
            return;
        }
        if let Some(from) = self.tracked {
            self.live.pointer_delta += Vec2::new(position.x - from.x, from.y - position.y);
        }
        self.tracked = Some(position);
        self.live.pointer = position;
    }

    /// The first touch is the pointer: where it lands and the primary mouse
    /// button, so a tap is a click wherever one would be.
    fn touch(&mut self, touch: &winit::event::Touch) {
        let at = Vec2::new(touch.location.x as f32, touch.location.y as f32);
        let primary = Switch::Mouse(MouseButton::Left);

        match touch.phase {
            TouchPhase::Started if self.touch.is_none() => {
                self.touch = Some(touch.id);
                self.tracked = None;
                self.point_at(at);
                self.press(primary, true);
            }
            TouchPhase::Moved if self.touch == Some(touch.id) => self.point_at(at),
            TouchPhase::Ended | TouchPhase::Cancelled if self.touch == Some(touch.id) => {
                self.touch = None;
                self.press(primary, false);
            }
            _ => {}
        }
    }
}

fn weigh(held: bool) -> f32 {
    match held {
        true => 1.0,
        false => 0.0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use winit::dpi::PhysicalPosition;
    use winit::event::{DeviceId, ElementState, Touch};

    use crate::input::binding::{ButtonAxis, ButtonAxis2};
    use crate::platform::Platform;

    /// The interval these tests count a second press by.
    const WITHIN: Duration = Duration::from_millis(400);

    const JUMP: [ButtonBinding; 2] = [
        ButtonBinding::Key(Key::Space),
        ButtonBinding::Pad(Pad::South),
    ];

    /// A reading holding whatever a test placed in it.
    fn reading(fill: impl FnOnce(&mut Reading)) -> Reading {
        let mut reading = Reading::default();
        fill(&mut reading);
        reading
    }

    fn snapshot(before: Reading, now: Reading) -> Snapshot {
        Snapshot { now, before }
    }

    // winit 0.30 keeps `KeyEvent`'s platform field private, so no crate can
    // build one; the keyboard is covered through its mapping and its state.
    fn click(state: ElementState) -> WindowEvent {
        WindowEvent::MouseInput {
            device_id: DeviceId::dummy(),
            state,
            button: winit::event::MouseButton::Left,
        }
    }

    fn cursor_at(x: f64, y: f64) -> WindowEvent {
        WindowEvent::CursorMoved {
            device_id: DeviceId::dummy(),
            position: PhysicalPosition::new(x, y),
        }
    }

    fn wheel(delta: MouseScrollDelta) -> WindowEvent {
        WindowEvent::MouseWheel {
            device_id: DeviceId::dummy(),
            delta,
            phase: TouchPhase::Moved,
        }
    }

    /// What a window reports for a wheel turned `lines` away from the
    /// player: winit counts a turn away up.
    fn rolled_away(lines: f32) -> MouseScrollDelta {
        MouseScrollDelta::LineDelta(0.0, lines)
    }

    /// What a window reports for a wheel tilted `lines` to the right:
    /// winit counts a tilt to the right down, the way X11 numbers its two
    /// buttons for it.
    fn tilted_right(lines: f32) -> MouseScrollDelta {
        MouseScrollDelta::LineDelta(-lines, 0.0)
    }

    /// What a window reports for a device that counts in pixels, turned
    /// `pixels` away from the player.
    fn scrolled_away(pixels: f64) -> MouseScrollDelta {
        MouseScrollDelta::PixelDelta(PhysicalPosition::new(0.0, pixels))
    }

    /// A device's own report that it moved, counted right and down as a
    /// window counts a position.
    fn motion(x: f64, y: f64) -> DeviceEvent {
        DeviceEvent::MouseMotion { delta: (x, y) }
    }

    fn touch_at(phase: TouchPhase, id: u64, x: f64, y: f64) -> WindowEvent {
        WindowEvent::Touch(Touch {
            device_id: DeviceId::dummy(),
            phase,
            location: PhysicalPosition::new(x, y),
            force: None,
            id,
        })
    }

    /// One frame of `events`, over the devices `before` them, as the
    /// controls it closes with.
    fn seen(devices: &mut Devices, events: &[WindowEvent]) -> Controls {
        for event in events {
            devices.see(event);
        }
        devices.sample(Duration::ZERO)
    }

    /// Presses `control` and releases it over two frames, the first of them
    /// at `at`, and returns the presses in a row that press was the last of,
    /// read through `control` itself.
    fn clicked(devices: &mut Devices, control: Switch, at: Duration) -> u32 {
        devices.press(control, true);
        let clicks = devices.sample(at).clicks(&[bound(control)]);

        devices.press(control, false);
        devices.sample(at);
        clicks
    }

    /// `control` as the binding an action reads it through.
    fn bound(control: Switch) -> ButtonBinding {
        match control {
            Switch::Key(key) => ButtonBinding::Key(key),
            Switch::Mouse(button) => ButtonBinding::Mouse(button),
        }
    }

    #[test]
    fn presses_of_one_control_within_the_interval_count_up_and_start_again_past_it() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let left = Switch::Mouse(MouseButton::Left);

        assert_eq!(clicked(&mut devices, left, Duration::ZERO), 1, "one press");
        assert_eq!(
            clicked(&mut devices, left, WITHIN),
            2,
            "a second inside the interval is a double click"
        );
        assert_eq!(
            clicked(&mut devices, left, WITHIN * 2 + Duration::from_millis(1)),
            1,
            "and one a millisecond past it starts a run of its own"
        );
    }

    #[test]
    fn a_control_pressed_beside_another_leaves_each_action_the_count_of_its_own() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let left = Switch::Mouse(MouseButton::Left);
        let space = Switch::Key(Key::Space);
        let selecting = [bound(left)];
        let jumping = [bound(space)];

        clicked(&mut devices, left, Duration::ZERO);
        assert_eq!(
            clicked(&mut devices, left, Duration::from_millis(100)),
            2,
            "the button has a count of two"
        );

        devices.press(left, true);
        devices.press(space, true);
        let sample = devices.sample(Duration::from_millis(200));

        assert_eq!(sample.clicks(&jumping), 1, "the key counts its own press");
        assert_eq!(
            sample.clicks(&selecting),
            0,
            "and the button reads none of the key's count"
        );

        devices.press(left, false);
        devices.press(space, false);
        devices.sample(Duration::from_millis(250));
        devices.press(left, true);
        let sample = devices.sample(Duration::from_millis(300));

        assert_eq!(
            sample.clicks(&selecting),
            1,
            "the button counts its own press again"
        );
        assert_eq!(
            sample.clicks(&jumping),
            0,
            "and the key reads none of the button's count"
        );
    }

    #[test]
    fn a_press_of_another_control_starts_the_count_again() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let left = Switch::Mouse(MouseButton::Left);
        let right = Switch::Mouse(MouseButton::Right);

        assert_eq!(clicked(&mut devices, left, Duration::ZERO), 1);
        assert_eq!(clicked(&mut devices, left, Duration::from_millis(100)), 2);
        assert_eq!(
            clicked(&mut devices, right, Duration::from_millis(200)),
            1,
            "another control counts as one press, however soon it is pressed"
        );
        assert_eq!(
            clicked(&mut devices, left, Duration::from_millis(300)),
            1,
            "and the one before it starts over too"
        );
    }

    #[test]
    fn an_edge_belongs_to_the_frame_the_control_changed_in() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);

        let held = [ButtonBinding::Mouse(MouseButton::Left)];
        let pressed = seen(&mut devices, &[click(ElementState::Pressed)]);
        assert!(pressed.frame().down(&held) && pressed.frame().pressed(&held));

        let still = seen(&mut devices, &[]);
        assert!(still.frame().down(&held), "still held across frames");
        assert!(!still.frame().pressed(&held), "the edge is spent");

        let released = seen(&mut devices, &[click(ElementState::Released)]);
        assert!(!released.frame().down(&held) && released.frame().released(&held));

        assert!(!seen(&mut devices, &[]).frame().released(&held));
    }

    #[test]
    fn a_frame_that_runs_no_ticks_keeps_its_edges_for_the_ticks_after_it() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let mut ticks = Ticks::default();
        let held = [ButtonBinding::Mouse(MouseButton::Left)];

        ticks.fold(&seen(&mut devices, &[click(ElementState::Pressed)]));
        let over = seen(&mut devices, &[]);
        ticks.fold(&over);
        assert!(
            !over.frame().pressed(&held),
            "the frame that saw the press is over"
        );
        assert!(
            ticks.snapshot().pressed(&held),
            "and no tick has read it yet"
        );

        ticks.ticked();
        assert!(
            !ticks.snapshot().pressed(&held),
            "the ticks that read it are the only ones that do"
        );

        ticks.fold(&seen(&mut devices, &[click(ElementState::Released)]));
        ticks.fold(&seen(&mut devices, &[]));
        assert!(
            ticks.snapshot().released(&held),
            "and coming up waits for the ticks the same way"
        );

        ticks.ticked();
        ticks.fold(&seen(&mut devices, &[]));
        assert!(!ticks.snapshot().released(&held));
    }

    #[test]
    fn a_tap_made_while_no_ticks_ran_is_still_seen_by_the_ticks_after_it() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let mut ticks = Ticks::default();
        let held = [ButtonBinding::Mouse(MouseButton::Left)];

        ticks.fold(&seen(
            &mut devices,
            &[click(ElementState::Pressed), click(ElementState::Released)],
        ));
        ticks.fold(&seen(&mut devices, &[]));
        assert!(ticks.snapshot().pressed(&held), "the press is not lost");

        ticks.ticked();
        ticks.fold(&seen(&mut devices, &[]));
        assert!(ticks.snapshot().released(&held), "and comes back up");
    }

    #[test]
    fn a_tap_between_two_frames_is_still_seen_by_one_of_them() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);

        let held = [ButtonBinding::Mouse(MouseButton::Left)];
        let tapped = seen(
            &mut devices,
            &[click(ElementState::Pressed), click(ElementState::Released)],
        );
        assert!(tapped.frame().pressed(&held), "the press is not lost");

        assert!(
            seen(&mut devices, &[]).frame().released(&held),
            "and comes back up"
        );
    }

    #[test]
    fn one_action_over_two_controls_takes_one_edge_at_a_time() {
        let held = snapshot(
            reading(|reading| reading.press_pad(Pad::South)),
            reading(|reading| {
                reading.press_pad(Pad::South);
                reading.pressed.keys[Key::Space.index()] = true;
            }),
        );

        assert!(held.down(&JUMP));
        assert!(
            !held.pressed(&JUMP),
            "the second control joins an action already down"
        );
    }

    #[test]
    fn the_pointer_reports_where_it_is_and_how_far_it_moved() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);

        let placed = seen(&mut devices, &[cursor_at(10.0, 20.0)]);
        assert_eq!(placed.frame().pointer(), Vec2::new(10.0, 20.0));

        let sideways = [AxisBinding::pointer_delta(PointerDelta::Sideways)];
        let upward = [AxisBinding::pointer_delta(PointerDelta::Up)];
        let moved = seen(&mut devices, &[cursor_at(14.0, 18.0)]);
        assert_eq!(moved.frame().axis(&sideways), 4.0);
        assert!(moved.frame().axis(&upward) > 0.0, "up the screen counts up");

        let still = seen(&mut devices, &[]);
        assert_eq!(still.frame().pointer(), Vec2::new(14.0, 18.0));
        assert_eq!(still.frame().axis(&sideways), 0.0, "movement is spent");
    }

    #[test]
    fn a_pointer_lane_reads_the_distance_it_moved_while_a_pad_lane_stops_at_its_own_end() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let look = [AxisBinding::pointer_delta(PointerDelta::Sideways).scale(0.01)];

        seen(&mut devices, &[cursor_at(0.0, 0.0)]);
        let moved = seen(&mut devices, &[cursor_at(500.0, 0.0)]);
        assert_eq!(
            moved.frame().axis(&look),
            5.0,
            "five hundred pixels at a hundredth each"
        );

        let pushed = snapshot(
            Reading::default(),
            reading(|reading| reading.push_pad(PadAxis::LeftX, 1.0)),
        );
        let lane = [AxisBinding::pad(PadAxis::LeftX).scale(4.0)];
        assert_eq!(pushed.axis(&lane), 1.0, "and a pad lane reads one at most");
    }

    #[test]
    fn an_action_bound_to_a_stick_and_the_pointer_reads_the_one_pushed_furthest() {
        let bindings = [
            Axis2Binding::stick(Stick::Left).deadzone(0.0),
            Axis2Binding::pointer().scale(0.01),
        ];
        let nudged = snapshot(
            Reading::default(),
            reading(|reading| {
                reading.push_pad(PadAxis::LeftX, 0.5);
                reading.pointer_delta = Vec2::new(20.0, 0.0);
            }),
        );
        assert_eq!(
            nudged.axis2(&bindings),
            Vec2::new(0.5, 0.0),
            "the stick, over a pointer barely moved"
        );

        let swept = snapshot(
            Reading::default(),
            reading(|reading| {
                reading.push_pad(PadAxis::LeftX, 1.0);
                reading.pointer_delta = Vec2::new(500.0, 0.0);
            }),
        );
        assert_eq!(
            swept.axis2(&bindings),
            Vec2::new(5.0, 0.0),
            "and the pointer, which reaches past the stick's own end"
        );
    }

    #[test]
    fn a_held_pointer_reads_the_movement_its_device_reports_as_a_window_pointer_reads_its_own() {
        let sideways = [AxisBinding::pointer_delta(PointerDelta::Sideways)];
        let upward = [AxisBinding::pointer_delta(PointerDelta::Up)];

        let mut window = Devices::new(Pads::silent(), WITHIN);
        seen(&mut window, &[cursor_at(10.0, 20.0)]);
        let placed = seen(&mut window, &[cursor_at(10.5, 19.5)]);

        let mut devices = Devices::new(Pads::silent(), WITHIN);
        devices.hold_pointer(true);
        devices.see_device(&motion(0.5, -0.5));
        let held = devices.sample(Duration::ZERO);

        assert_eq!(held.frame().axis(&sideways), placed.frame().axis(&sideways));
        assert_eq!(held.frame().axis(&upward), placed.frame().axis(&upward));
        assert!(held.frame().axis(&upward) > 0.0, "up the screen counts up");
    }

    #[test]
    fn a_held_pointer_counts_its_movement_once_and_stays_where_it_was_held() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        seen(&mut devices, &[cursor_at(10.0, 20.0)]);
        devices.hold_pointer(true);

        devices.see_device(&motion(0.5, 0.0));
        devices.see(&cursor_at(14.0, 20.0));
        let held = devices.sample(Duration::ZERO);

        let sideways = [AxisBinding::pointer_delta(PointerDelta::Sideways)];
        assert_eq!(
            held.frame().axis(&sideways),
            0.5,
            "the device's own movement, and not the window's report over it"
        );
        assert_eq!(
            held.frame().pointer(),
            Vec2::new(10.0, 20.0),
            "and the place it was held at"
        );
    }

    #[test]
    fn a_released_pointer_measures_its_next_movement_from_where_the_window_reports_it() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let sideways = [AxisBinding::pointer_delta(PointerDelta::Sideways)];

        seen(&mut devices, &[cursor_at(10.0, 20.0)]);
        devices.hold_pointer(true);
        seen(&mut devices, &[]);
        devices.hold_pointer(false);

        let placed = seen(&mut devices, &[cursor_at(400.0, 20.0)]);
        assert_eq!(
            placed.frame().axis(&sideways),
            0.0,
            "however far the hold left it from there"
        );

        devices.hold_pointer(false);
        let moved = seen(&mut devices, &[cursor_at(400.5, 20.0)]);
        assert_eq!(
            moved.frame().axis(&sideways),
            0.5,
            "and it moves from there, however often the release is set"
        );
    }

    #[test]
    fn a_window_that_loses_focus_loses_its_hold_on_the_pointer() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let sideways = [AxisBinding::pointer_delta(PointerDelta::Sideways)];

        seen(&mut devices, &[cursor_at(10.0, 20.0)]);
        devices.hold_pointer(true);
        seen(&mut devices, &[WindowEvent::Focused(false)]);

        let placed = seen(&mut devices, &[cursor_at(400.0, 20.0)]);
        assert_eq!(
            placed.frame().pointer(),
            Vec2::new(400.0, 20.0),
            "the window places the pointer again"
        );

        let moved = seen(&mut devices, &[cursor_at(400.5, 20.0)]);
        assert_eq!(
            moved.frame().axis(&sideways),
            0.5,
            "and its movement reads through again"
        );
    }

    #[test]
    fn a_pointer_nothing_holds_reads_none_of_the_movement_its_device_reports() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        seen(&mut devices, &[cursor_at(10.0, 20.0)]);

        devices.see_device(&motion(0.5, 0.0));
        devices.see(&cursor_at(10.5, 20.0));
        let moved = devices.sample(Duration::ZERO);

        let sideways = [AxisBinding::pointer_delta(PointerDelta::Sideways)];
        assert_eq!(moved.frame().axis(&sideways), 0.5, "the window's alone");
    }

    #[test]
    fn the_first_touch_is_the_pointer_and_its_primary_button() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let held = [ButtonBinding::Mouse(MouseButton::Left)];

        let touched = seen(
            &mut devices,
            &[touch_at(TouchPhase::Started, 1, 40.0, 60.0)],
        );
        assert_eq!(touched.frame().pointer(), Vec2::new(40.0, 60.0));
        assert!(touched.frame().pressed(&held));

        let moved = seen(
            &mut devices,
            &[
                touch_at(TouchPhase::Started, 2, 0.0, 0.0),
                touch_at(TouchPhase::Moved, 1, 44.0, 60.0),
            ],
        );
        assert_eq!(
            moved.frame().pointer(),
            Vec2::new(44.0, 60.0),
            "a second touch is not the pointer"
        );

        let ended = seen(&mut devices, &[touch_at(TouchPhase::Ended, 1, 44.0, 60.0)]);
        assert!(ended.frame().released(&held));
    }

    #[test]
    fn a_window_that_loses_focus_cannot_leave_a_control_stuck() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        seen(&mut devices, &[click(ElementState::Pressed)]);

        let unfocused = seen(&mut devices, &[WindowEvent::Focused(false)]);

        let held = [ButtonBinding::Mouse(MouseButton::Left)];
        assert!(!unfocused.frame().down(&held));
    }

    #[test]
    fn two_buttons_make_an_axis_and_four_make_a_vector() {
        let walking = reading(|reading| {
            reading.pressed.keys[Key::D.index()] = true;
            reading.pressed.keys[Key::W.index()] = true;
        });
        let snapshot = snapshot(Reading::default(), walking);

        assert_eq!(
            snapshot.axis(&[AxisBinding::from(ButtonAxis {
                negative: Key::A,
                positive: Key::D
            })]),
            1.0
        );
        assert_eq!(
            snapshot.axis(&[AxisBinding::from(ButtonAxis {
                negative: Key::D,
                positive: Key::A
            })]),
            -1.0
        );

        let wasd = [Axis2Binding::from(ButtonAxis2 {
            left: Key::A,
            right: Key::D,
            down: Key::S,
            up: Key::W,
        })];
        let walk = snapshot.axis2(&wasd);
        assert!((walk.length() - 1.0).abs() < 1e-6, "{walk} is one long");
        assert!(walk.x > 0.0 && walk.y > 0.0, "{walk} points up and right");
    }

    #[test]
    fn the_control_pushed_furthest_is_the_one_an_action_reads() {
        let leaning = reading(|reading| {
            reading.push_pad(PadAxis::LeftX, 0.5);
            reading.pressed.keys[Key::A.index()] = true;
        });
        let snapshot = snapshot(Reading::default(), leaning);

        let bindings = [
            AxisBinding::pad(PadAxis::LeftX).deadzone(0.0),
            AxisBinding::from(ButtonAxis {
                negative: Key::A,
                positive: Key::D,
            }),
        ];
        assert_eq!(snapshot.axis(&bindings), -1.0, "the key is pushed further");
        assert_eq!(
            snapshot.axis(&bindings[..1]),
            0.5,
            "on its own the stick is"
        );
    }

    #[test]
    fn a_pad_lane_reads_the_device_pushing_it_furthest() {
        let both = reading(|reading| {
            reading.push_pad(PadAxis::LeftX, 0.4);
            reading.push_pad(PadAxis::LeftX, -0.9);
            reading.push_pad(PadAxis::LeftX, 0.2);
            reading.push_joystick(JoystickControl::new(3), 0.6);
            reading.push_joystick(JoystickControl::new(3), 0.1);
        });

        assert_eq!(both.pad_axes[PadAxis::LeftX.index()], -0.9);
        assert_eq!(both.joystick_axes.value(JoystickControl::new(3)), 0.6);
        assert_eq!(
            both.joystick_axes.value(JoystickControl::new(4)),
            0.0,
            "and nothing for the rest"
        );
    }

    #[test]
    fn capture_answers_with_the_control_the_player_just_moved() {
        let quiet = Reading::default();
        let pushed = reading(|reading| {
            reading.press_pad(Pad::Start);
            reading.push_pad(PadAxis::RightX, 0.8);
            reading.push_joystick(JoystickControl::new(11), 0.9);
        });
        let snapshot = snapshot(quiet, pushed);

        assert_eq!(
            snapshot.actuated_button(),
            Some(ButtonBinding::Pad(Pad::Start))
        );
        assert_eq!(
            snapshot.actuated_axis(),
            Some(AxisBinding::pad(PadAxis::RightX))
        );
        assert_eq!(
            snapshot.actuated_axis2(),
            Some(Axis2Binding::stick(Stick::Right))
        );

        let still = Snapshot {
            before: pushed,
            now: pushed,
        };
        assert_eq!(still.actuated_button(), None, "a held control is not new");
        assert_eq!(still.actuated_axis(), None);
        assert_eq!(still.actuated_axis2(), None);
    }

    #[test]
    fn capture_is_deaf_to_a_control_that_has_barely_moved() {
        let nudged = reading(|reading| reading.push_pad(PadAxis::LeftY, ACTUATED));
        let snapshot = snapshot(Reading::default(), nudged);

        assert_eq!(snapshot.actuated_axis(), None);
        assert_eq!(snapshot.actuated_axis2(), None);
    }

    #[test]
    fn one_notch_reads_as_one_however_the_platform_counts_a_turn() {
        let browser = Platform::Browser.wheel_rate();
        let desktop = Platform::Desktop.wheel_rate();

        assert_eq!(
            browser.notches(rolled_away(3.0)),
            Vec2::new(0.0, 1.0),
            "three lines are a notch in a browser"
        );
        assert_eq!(
            browser.notches(scrolled_away(100.0)),
            Vec2::new(0.0, 1.0),
            "and so are 100 pixels"
        );
        assert_eq!(
            desktop.notches(rolled_away(1.0)),
            Vec2::new(0.0, 1.0),
            "one line is a notch on the desktop"
        );
        assert_eq!(
            desktop.notches(scrolled_away(100.0)),
            Vec2::new(0.0, 1.0),
            "and 100 pixels are one there too"
        );
    }

    #[test]
    fn a_roll_away_and_a_tilt_to_the_right_each_read_positive() {
        let rate = Platform::Desktop.wheel_rate();

        assert_eq!(rate.notches(rolled_away(1.0)), Vec2::new(0.0, 1.0));
        assert_eq!(rate.notches(tilted_right(1.0)), Vec2::new(1.0, 0.0));
        assert_eq!(
            rate.notches(rolled_away(-1.0)),
            Vec2::new(0.0, -1.0),
            "and a roll toward the player reads the other way round"
        );
    }

    #[test]
    fn a_tilt_reaches_the_sideways_lane_and_a_roll_the_upward_one() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let sideways = [AxisBinding::wheel(WheelDelta::Sideways)];
        let upward = [AxisBinding::wheel(WheelDelta::Up)];

        let tilted = seen(&mut devices, &[wheel(tilted_right(1.0))]);
        assert_eq!(tilted.frame().axis(&sideways), 1.0);
        assert_eq!(tilted.frame().axis(&upward), 0.0, "and nothing rolled");

        let rolled = seen(&mut devices, &[wheel(rolled_away(1.0))]);
        assert_eq!(rolled.frame().axis(&upward), 1.0);
        assert_eq!(rolled.frame().axis(&sideways), 0.0, "nothing tilted");

        let still = seen(&mut devices, &[]);
        assert_eq!(
            still.frame().axis(&upward),
            0.0,
            "and a turn lasts one reading"
        );
    }

    #[test]
    fn the_wheel_reads_as_one_vector_with_the_tilt_as_x_and_the_roll_as_y() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        let wheel_vector = [Axis2Binding::wheel()];

        let turned = seen(
            &mut devices,
            &[wheel(tilted_right(1.0)), wheel(rolled_away(3.0))],
        );
        assert_eq!(turned.frame().axis2(&wheel_vector), Vec2::new(1.0, 3.0));
        assert_eq!(
            turned.frame().actuated_axis2(),
            None,
            "and a turn that far is never captured"
        );

        let still = seen(&mut devices, &[]);
        assert_eq!(
            still.frame().axis2(&wheel_vector),
            Vec2::ZERO,
            "a turn lasts one reading"
        );
    }

    #[test]
    fn a_pointer_is_never_captured_however_far_it_is_moved() {
        let mut devices = Devices::new(Pads::silent(), WITHIN);
        seen(&mut devices, &[cursor_at(0.0, 0.0)]);
        let moved = seen(&mut devices, &[cursor_at(400.0, 400.0)]);

        assert_eq!(moved.frame().actuated_axis(), None);
        assert_eq!(moved.frame().actuated_axis2(), None);
    }
}