upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/docs/gameinput.md
blob: 968e4bb07f3c936600f7a65842c23c3024f51fde (plain)
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
# Controller input: the GameInput shim on SDL3

The Xbox build reads controllers through Microsoft's GameInput API. `runtime/shims/gameinput.cpp` answers
`GameInputCreate` with its own implementation of that API, backed by [SDL3](https://libsdl.org) gamepads, so
every controller SDL supports works the way an Xbox pad would: DualSense, DualShock 4, Switch Pro, Xbox pads, and the
rest of SDL's controller database. On a DualSense the impulse-trigger rumble becomes adaptive-trigger effects, and
the lightbar colour can be set.

Without the shim the loader would bind `GameInputCreate` to the host's `GameInput.dll` if there is one
([#279](https://github.com/ItsNotRexed/Leonida/pull/279)). That works for Xbox pads only, and gives no DualSense
features. That path is tested without the game: `gameinput_host_test` (ctest `gameinput_host`) maps a synthetic DLL
built against the SDK's `gameinput.lib` and checks that its `GameInput.dll` import binds to the host's copy, that
`GameInputCreate` and `GetCurrentTimestamp` work from mapped code, and that `GetCurrentReading` answers; with a pad
attached, `GetGamepadState` must succeed on the reading. It passes on Windows 11 build 26300 (GameInput 0.2309) without
a pad attached. The test skips only where Windows cannot load `GameInput.dll`; with the DLL present, an import that binds to nothing fails it. The game executable is not available yet,
so whether it imports GameInput this way, and under which
module, is unverified (see [VERIFY](#verify)).

### Diagnosing a native host failure

If `gameinput_host` binds to the host DLL but `GameInputCreate` fails, call `GameInputCreate` directly from the absolute
`%WINDIR%\System32\GameInput.dll` path, outside the mapped path. A matching failure shows that the call can fail
without Leonida's loader, but does not identify the underlying cause or rule out every concurrent loader issue. A
failed call alone is not evidence that the GameInput service is absent or stopped. Once Windows loads the DLL, keep
the host test failure visible; do not skip it.

## Building

The shim is optional, and the build downloads nothing unless asked. SDL3 is zlib-licensed. CMake builds the shim when
SDL3 is available in one of these ways:

- **Installed SDL3**, 3.2 or newer, found by `find_package(SDL3)`: set `SDL3_DIR` or `CMAKE_PREFIX_PATH`, for example
  `-DSDL3_DIR=C:/SDL3/cmake`. No flag is needed.
- **`-DLEONIDA_SDL3_FETCH=ON`**: downloads the pinned release `SDL3-3.4.20.tar.gz` from SDL's GitHub releases once at
  configure time, checks its SHA-256, and builds it static with only the gamepad parts (no audio, video, GPU or
  render). That takes about a minute on the first build. `scripts/build_runtime.ps1 -FetchSdl3` passes it.
- **A local copy of that tarball**: extract it and pass `-DFETCHCONTENT_SOURCE_DIR_SDL3=<path to SDL3-3.4.20>`; it is
  built the same way, without a download.

Without any of these, or with `-DLEONIDA_SDL3=OFF`, configure prints a message and `gta6rt` is built without the SDL3
shim. It links `runtime/shims/gameinput_no_sdl.cpp` instead, which still serves `GameInputCreate` (by name and as
`gameinput.dll!#1`): with no devices, or with `LEONIDA_INPUT_SCRIPT` set with one scripted pad (see
[Scripted input without SDL3](#scripted-input-without-sdl3)). `gameinput_test` and `gameinput_probe` are not built,
and CTest lists `gameinput` and `gameinput_script` as not run (disabled) rather than failing; `gameinput_no_sdl` and
`gameinput_no_sdl_script` run instead.

### Scripted input without SDL3

The Windows artifacts of CI and offline builds have no SDL3. Without a device, the title waits at its first "press A"
prompt forever, so no headless or CI run could get past it. With `LEONIDA_INPUT_SCRIPT` set, such a build serves one
scripted pad, driven by the script alone:

- **The device:** an Xbox One gamepad named `Scripted pad (Leonida)`, connected from the first `GameInputCreate`. It
  is reported by `RegisterDeviceCallback` enumeration (blocking on the caller's thread, async from a thread of the
  shim, or through `IGameInputDispatcher::Dispatch` once the title made a dispatcher) and found by `FindDeviceFromId`.
  It is already connected, so a callback registered without enumeration hears nothing.
- **The readings:** `GetCurrentReading`, `GetNextReading` and `GetPreviousReading`, with gamepad, UI navigation,
  controller axis and controller button state. A reading is taken when the title asks for one, so no thread polls,
  but it first adds one reading for every change the script made since the last, stamped with the script's own time:
  a press that starts and ends between two reads of the title is still in the history, where `GetNextReading` finds
  it, and the readings are the same however often the title reads. The history keeps the last 64 readings.
- **The timeline:** the same as with SDL3 (`runtime/shims/gameinput_script.h` holds the parser, the timeline and the
  log lines for both): seconds from the first `GameInputCreate`, each press held 300 ms (or its own `:hold`, see
  `LEONIDA_INPUT_SCRIPT` below), then released.
- **Not served:** reading callbacks, aggregate devices, rumble and every other device. Those slots answer `E_NOTIMPL`
  and log the slot once. Controllers and the [keyboard pad](#keyboard-pad) still need SDL3.

The start of the run logs one line with the counts, and each press logs the same lines as with SDL3:

```text
[rt] gameinput: served without SDL3: one scripted pad for LEONIDA_INPUT_SCRIPT (3 scripted press(es), 0 rejected); controllers and the keyboard pad need SDL3
[rt] gameinput: scripted press of button 0 at 40.0 s
[rt] gameinput: press a@40.0 (Scripted pad (Leonida))
```

A press is logged at the next reading the title asks for, with the script's time of the press, so a press is logged
once the title reads its pad again. `LEONIDA_INPUT_LOG=0` turns the `press` lines off. `LEONIDA_INPUT_TRACE=1`
(diagnostic, this shim only) logs what the title asks for: the first 128 `GetCurrentReading`, `GetNextReading` and
`GetPreviousReading` calls, then every one that returns a pressed button and every 1000th, the device callbacks and
`RegisterDeviceCallback` calls, and the first few calls of each reading method. Without `LEONIDA_INPUT_SCRIPT`, the shim serves no devices and answers `E_NOTIMPL` for
every slot past `Release`, as before.

`LEONIDA_INPUT_FILE=<path>` drives a run whose display takes no keyboard input (a headless session): every line
appended to that file names one button of the script's table (`a`, `down`, ...) and becomes a press at once, held
like a scripted one. The file is read again at most every 250 ms. It is for local runs only.

`scripts/build_runtime.ps1` (what `make_game.py` runs) builds the shim only on its CMake path, when Visual Studio's
C++ CMake tools are installed. Its direct-`cl.exe` fallback compiles a fixed file list without the shim and warns
about it. `make_game.py`'s runtime stage on Windows runs it with `-FetchSdl3`, so a build made the usual way has
controller, keyboard and mouse input; `--no-sdl3` leaves the download out (an installed SDL3 is still used).

## Mapping

GameInput's buttons are positional, as on an Xbox pad, and SDL's are too, so the face buttons go by position, not by
label:

| GameInput | SDL3 | DualSense | Switch Pro |
|---|---|---|---|
| `A` | south | Cross | B |
| `B` | east | Circle | A |
| `X` | west | Square | Y |
| `Y` | north | Triangle | X |
| `View` | back | Create | Minus |
| `Menu` | start | Options | Plus |
| shoulders, stick clicks, d-pad | same | L1/R1, L3/R3, d-pad | L/R, stick clicks, d-pad |
| guide button callback | guide | PS | Home |

The DualSense touchpad click, mute button and paddles are not in GameInput's gamepad state; they are in the
controller-button array (`GetControllerButtonState`, indexed in SDL's `SDL_GamepadButton` order).

- Sticks: -1..1 with +Y up (SDL reports +Y down; the shim flips it). Triggers: 0..1. No deadzone is applied, as on
  console: the title applies its own.
- `GetUiNavigationState` is derived from the pad: A accept, B cancel, X/Y context 1/2, stick clicks context 3/4, d-pad
  or left stick past half for up/down/left/right, shoulders for page left/right, triggers past half for page up/down,
  right stick past half for scrolling, Menu and View as themselves.
- Controller axes (`GetControllerAxisState`): LX, LY, RX, RY, LT, RT in 0..1, sticks at rest at 0.5.
- Every pad is reported as family `GameInputFamilyXboxOne` with its real USB vendor and product id.
- Player LEDs (and SDL's default lightbar colour) follow connection order: the first pad is player 1, and a pad
  plugged in later takes the lowest free slot.

## Keyboard pad

The title reads gamepads only, so keyboard input has to arrive as a gamepad. The shim attaches one SDL virtual
gamepad named `Keyboard pad (Leonida)` and presses its buttons from the keyboard on every poll. It then goes
through the same path as a real pad: a device object, the next free player slot, readings, reading and device
callbacks, and UI navigation derived from its buttons. It reports no rumble motors. It is on by default in the
focused mode, so a player without a pad can still play; `LEONIDA_KEYBOARD_PAD=off` removes it.

If SDL fails to attach or open the keyboard pad, the shim retries after one second while the pad is
enabled. Only the first failure in a continuous series is logged; turning the pad off and back on retries immediately.

| key | button |
|---|---|
| arrow keys | d-pad |
| Enter | `A` |
| Backspace | `B` |
| X | `X` |
| Y | `Y` |
| Q / E | left / right shoulder |
| Esc | `Menu` |
| Tab | `View` |
| W / A / S / D | left stick up / left / down / right |
| mouse movement | right stick |
| right mouse button | left trigger (aim) |
| left mouse button | right trigger (fire) |

Letters are Windows virtual-key codes, so `Y` is the key labelled Y on the active layout (it sits where Z does on a
QWERTY keyboard with a German layout). Mouse buttons are the physical ones: `GetAsyncKeyState` ignores the
swapped-buttons setting.

WASD pushes the left stick to full deflection. Opposite keys cancel (W+S is centered on Y), and a diagonal sits on
the round gate as a real stick reports it: about 0.707 on each axis, not 1.

The right stick follows the mouse's movement, not the cursor's position. Each poll (2 ms with the background thread)
the stick keeps 7/8 of its value and adds 1024 axis units (of 32767, times `LEONIDA_MOUSE_SENSITIVITY`) per count the mouse moved since the last poll,
clamped to full. Steady movement of 4 counts a poll (2000 a second) is full deflection; when the mouse stops, the
stick falls back from full to exactly 0 in 67 polls (134 ms). Moving the mouse down pushes the stick down.

The movement comes from raw input (`WM_INPUT`): what the mouse itself reports, so it does not stop at the edge of the
screen and Windows' pointer acceleration does not change it. When the keyboard pad attaches, the shim starts one
thread with a message-only window (never shown) registered for raw mouse input (`RIDEV_INPUTSINK`), which adds each
relative movement to a running total; the poll takes the difference of that total between polls. Absolute reports
(remote desktop, some virtual machines, pen tablets) are ignored. If the window or the registration fails, the shim
logs it and falls back to `GetCursorPos` deltas, which stop at the screen edge. A count is one step of the mouse's
sensor, about a pixel at Windows' default pointer speed without acceleration, so the feel depends on the mouse's DPI.

With raw input on and a window of this process in the foreground, the cursor is kept inside that window's client
area (`ClipCursor`, re-applied every 100 ms) so that a click cannot land on another window; it is released when focus
moves away or the keyboard pad is turned off. It is also released while the window is moved or sized, while a
menu loop runs, and while a mouse press that began outside the client area (on the title bar or a border) is held, so
the window can still be dragged; it comes back once the button is released. The cursor stays visible: hiding it has to happen on the thread that
owns the game's window, which is the title's, not the shim's.

Keys are read with `GetAsyncKeyState`, which needs no window or message loop (SDL's keyboard is part of its video
subsystem, which this build leaves out) and works under Wine. By default (or with `LEONIDA_KEYBOARD_PAD=1`), keys
count only while a window of this process is in the foreground. Losing focus releases keyboard and mouse input.
The cursor is read afresh on return so the right stick does not jump. Scripted presses run with or without focus
for unattended runs.
`LEONIDA_KEYBOARD_PAD=always` reads physical input whatever has focus; a console tool such as
  `gameinput_probe` needs it, because its console window belongs to the terminal, not to the tool.
- Force feedback and haptics run through a fake haptic backend (`rt::gameinput::set_haptic_source`), because SDL's
  virtual joysticks report no haptics: the motor count, axes and effect flags a wheel reports, and a pad without SDL
  haptics reporting no motor at all; `CreateForceFeedbackEffect` and its `E_INVALIDARG` cases; a constant effect
  becoming `SDL_HAPTIC_CONSTANT` at the right level, not re-sent while unchanged, updated once when the parameters
  change; the effect's gain and the motor's device gain; a 50 Hz sine's period, phase, length and play count; a
  spring's coefficients, saturations, dead zone and centre; a finished effect reporting stopped; `Paused` stopping it;
  `LEONIDA_RUMBLE=0` silencing it and the mute lifting; the SDL effect destroyed when the title releases it; and, on a
  pad with trigger motors, the two haptic motors, `SetHapticMotorState`'s intensity, deadline, `playCount` 0 and null,
  and the trigger rumble sharing the one message.

To try it by hand: `set LEONIDA_KEYBOARD_PAD=always`, then `gameinput_probe --seconds 20` and press keys.

## The keyboard-and-mouse pad of the D3D12 runtime

The D3D12 runtime (`d3d12/`) has its own GameInput module (`d3d12/crates/leonida-hle/src/modules/gameinput.rs`)
with a stand-in pad made from the keyboard and mouse, present while no host pad is connected (or beside one, with
`LEONIDA_ONE_PAD`, the default). Keys and mouse buttons count only while a window of the runtime has focus.

### Grand Theft Auto V's layout: one table on foot, one in a vehicle

The title reads a pad only, and on a pad one button is two actions: the right trigger shoots on foot and accelerates
in a vehicle, the left trigger aims and brakes. One table of keys cannot be a PC layout then, so there are two
(`gameinput/kbm.rs`), and the stand-in pad uses the one of what the player is in. The keys are Grand Theft Auto V's
PC defaults (its key bindings as listed in BisectHosting's "GTA V controls guide" and on StrategyWiki's controls
page). The pad button of each action is the title's default pad layout as far as it is known: the table below is the
one that came with the PC prompt glyphs (a contributor's notes on the Xbox layout), not measured here.

| pad | on foot | in a vehicle |
|---|---|---|
| left stick, click | move, run | steer (lean on a bike), horn |
| right stick, click | camera, look behind (zoom while aiming) | camera, look behind |
| A / B / X / Y | jump and climb / crouch / melee and reload / interact, enter a vehicle | handbrake / duck, headlights / not known / leave the vehicle |
| LB / RB | loadout wheel, holster / cover | loadout wheel / shoot from the vehicle |
| LT / RT | aim / shoot | brake and reverse / accelerate |
| d-pad up, down, left, right | phone, HUD and objective, radio menu, partner menu | the same |
| Menu / View | pause / map | the same |

| key | on foot | in a vehicle |
|---|---|---|
| W, S | left stick up, down: move | RT, LT (fully): accelerate, brake and reverse |
| A, D | left stick left, right: move | the same: steer |
| mouse | right stick: camera (mouse look, below) | the same |
| left mouse button | RT: shoot | RB: shoot from the vehicle |
| right mouse button | LT: aim | nothing (the button that aims from a vehicle is not known) |
| Space | A: jump, climb | A: handbrake |
| Left Shift | left stick click: run | left stick up: lean forward on a bike, nose down in an aircraft |
| Left Ctrl | B: crouch (GTA V's stealth) | left stick down: lean back, nose up |
| Num 8, Num 5, Num 4, Num 6 | nothing | left stick up, down, left, right (GTA V's aircraft keys) |
| Q | RB: cover | d-pad left: radio menu (GTA V's radio wheel) |
| E | Y: interact (GTA V's context action) | left stick click: horn |
| F | Y: enter a vehicle | Y: leave it |
| R | X: reload, melee | X (the same button; GTA V's cinematic camera has none known) |
| X, H | nothing | B: duck, headlights |
| Tab | LB: loadout wheel (hold), holster | LB |
| C | right stick click: look behind | the same |
| M | View: map | the same |
| Esc, P | Menu: pause | the same |
| arrows | d-pad: phone (up) and its menus | the same |
| Enter, Backspace | A, B: accept and back in the phone and menus | the same |
| Z | d-pad down: HUD and objective (GTA V's radar zoom, the same press on its pad) | the same |
| Y; I J K L | Y; right stick (kept from the layout before; GTA V has nothing on them on foot) | the same |

GTA V keys left without a binding, because the title's pad button for the action is not known: V (camera view), G
(grenade; landing gear), O (heavy melee), the number keys (weapon slots), `[` `]` `,` `.` `=` `-` (zoom, radio), T, B,
N, the F keys (character switch), Insert, Page Up and Page Down, the middle mouse button, and Caps Lock (GTA V's
special ability), which is the switch described below. Left Alt (GTA V's character switch) would be the partner
menu, d-pad right, and is left out because every Alt+Tab would press it; the right arrow is that button. For the
same reason Tab, Enter, Space and Esc give nothing while an Alt key is down. The mouse wheel (GTA V's next and previous weapon, and zoom
while aiming) is not bound either: the pad has no button known for the next weapon, and the host source polls key
states (`GetAsyncKeyState`), which a wheel does not have; it would have to be counted from `WM_MOUSEWHEEL` in the
window procedure of `lifecycle.rs`. The layout before had Z and V as the triggers, X as X, H as a second right stick
click and Left Ctrl as a second left stick click; those went where GTA V has another meaning for the key.
`LEONIDA_KBM=classic` brings the table of before back whole (`FALLBACK_BUTTONS`: W A S D and I J K L the sticks,
Space or Enter A, R or Backspace B, X, F or Y, Q and E the shoulders, Left Shift or Left Ctrl and C or H the stick
clicks, Z or the right mouse button LT, V or the left mouse button RT, Esc Menu, Tab View).

In an aircraft A and D are the left stick (roll), not GTA V's rudder: only "in a vehicle" is known, not which kind.

### Which table counts

`gameinput::set_player_context(OnFoot | InVehicle | Unknown)` tells the stand-in pad, lock-free from any thread; a
context that is not set again for 500 ms is unknown (and the pad only lets go of a known one after 100 ms of
unknown). Unknown is the on-foot table, and then **Caps Lock** switches to the driving table and back by hand, with a
line in the log at every change of table; driving by hand also ends when F (leave the vehicle) is pressed, so that W
cannot stay the right trigger on foot. While a context is measured Caps Lock does nothing: it is GTA V's special
ability key, and a press out of habit on foot must not make W a shot. `gameinput::driving_controls()` says which
table is in use (for whoever draws key prompts).

**The hand-over** when the table changes: a key that is another pad input in the other table (W, S, the mouse buttons,
Left Shift, Left Ctrl, Q, E, X, H) and is down at that moment gives nothing until it has been let go and pressed
again, and no such key gives anything for 400 ms after the change (`LEONIDA_KBM_SETTLE_MS`, 0 to 3000). So the left
mouse button held on foot never becomes the accelerator and W held in a car never becomes a shot; the price is that W
held while getting in has to be pressed again to drive off. Keys that are the same pad input in both tables (A, D,
Space, F, ...) carry over as a real pad's button would. Unit-tested over every set of held keys in both directions
(`cargo test -p leonida-hle gameinput`).

**Who tells.** `d3d12/apps/leonida/src/player_context.rs` reads the title every 16 ms from a thread of its own
(`ReadProcessMemory` on the own process: nothing is written and no title code is called, so it does not need
`LEONIDA_GAME_ACTIONS=1`; without the game actions it looks the two globals up itself at start, two more passes over
the image's code, about 0.15 s together on the retail executable's 99.9 MB of code). It tells `Unknown` while there is no player ped, and a change counts after three equal reads. What
says "in a vehicle" is, in this order:

1. `LEONIDA_PED_VEHICLE_AT=0x<offset>`: a field of the player's ped that points at its vehicle and is null on foot.
   None is known (see below why there may be none), so this is unset by default.
2. The title's own global of the player's vehicle (`Site::PlayerVehicle` in `leonida-loader/src/game_actions.rs`,
   found by a pattern that is in the 1.0.2.1 executable once; `LEONIDA_PLAYER_VEHICLE_AT=0x<offset in the image>`
   names another, `=off` turns it off). **Read from the code, not yet seen in the running title:**
   - The title keeps what belongs to a ped apart from the ped's entity, in tables looked up by the entity's id
     (`+9Ch`; a ped's id has `60000h` under the mask `3E0000h`, its index is the low 17 bits, and a 16-bit slot of
     `FFFFh` means "none"). Its "the vehicle this ped is in" (the function at `4DD7510h`) takes column `47h` of
     those tables and gives the pointer at `+898h` of it when bit `20h` of the byte at `+10h` is set, else null: the
     shape of GTA V's `GetVehiclePedInside`, a "my vehicle" pointer that outlives the ride plus a flag. That is why a
     pointer in the ped that is null on foot may not exist at all.
   - The global at `AB760C8h` is written by one function (`CA4DE0h`), which has three callers: one passes a
     vehicle (in a function of 129Fh bytes, taken to be where a ped is put in a vehicle), one passes null after
     testing that the ped's id is the player's (taken to be where a ped is taken out), and the function that sets
     the player's ped passes what `4DD7510h` gives for the new ped. The first two are methods of that same column
     `47h` record: the first begins by reading its `+10h` and `+898h` and testing bit `20h`, the second tests
     other bits beside it (`+12h`). 167 places in the code read the global; the vehicle cheats read a type byte
     at `+FAh` of what it points at.
   - Not known until it has run: that it is null in every on-foot state (after a crash through the windscreen, a
     vehicle that blows up, a cutscene), and when during getting in and out it changes compared with the title's own
     switch of its controls. The reader logs every change with its time, and warns when the ped moves at 12 m/s for
     a second while it says "on foot", or the vehicle is 60 m from the ped while it says "in a vehicle".
3. `LEONIDA_KBM_SPEED=1`: the speed rule. From the ped's position (taken every 0.2 s): 12 m/s (43 km/h; a sprint is
   about 7) or more for a second without a break is "in a vehicle", until 3 s have passed below that speed; a fall
   (more down than along) and a jump of the position (a teleport, a respawn) do not count. Its limits are why it is
   off unless asked for: it never says "on foot" (a car at a red light and a ped standing are the same to it), it
   cannot see a drive begin, so it never switches from a standstill and the first metres of every drive are on the
   on-foot keys, and so the meaning of W and of the mouse buttons would change in the middle of a drive, at every
   stop. It always runs as the check named above.

With none of the three the context stays unknown: the on-foot table, and Caps Lock.

| switch | effect |
|---|---|
| `LEONIDA_KBM=classic` | the single table of before; nothing reads the title |
| `LEONIDA_KBM_DRIVE=on` / `off` / `auto` | forces the driving table on or off (a test; nothing reads the title and Caps Lock does nothing then); `auto` is the default |
| `LEONIDA_KBM_SETTLE_MS=<ms>` | the pause after a change of table, 400 |
| `LEONIDA_PED_VEHICLE_AT`, `LEONIDA_PLAYER_VEHICLE_AT`, `LEONIDA_KBM_SPEED` | what says "in a vehicle", above |
| `LEONIDA_PED_DUMP=<folder>` | for measuring: F8 in the game's window, or a file named `dump` in that folder (its text is the label), writes the first 4000h bytes of the player's ped to `ped-<date>-<time>-<label>.bin`, the first 1000h of the vehicle the global names to `vehicle-...bin`, and a line to `index.txt` (time, addresses, the ped's id, position, speed, what was read). The folder must be outside the repository; the files are the title's memory and are never committed. |

The mouse buttons are not passed to the title while the F1 settings menu or the F4 trainer menu is open, and they
never reach the title as keyboard keys.

**Mouse look (D3D12 runtime).** The console title turns its camera with the right stick only; it does not read the
mouse for that. A left click in the game window makes the window hold the mouse: the cursor is hidden and kept in the
window, and the mouse's motion becomes a right-stick push (`MouseLook` in `d3d12/crates/leonida-hle/src/modules/
gameinput.rs`): its speed over the last 40 ms, a full push at 1600 pixels a second, lifted past a 0.24 dead zone with a
0.6 power curve, merged with the pad's own stick. That click is not a shot; the mouse buttons reach the title as
triggers only while the window holds the mouse. Esc (which also pauses), the F1 or F4 menu, or another window in front
gives the mouse back. Settings: `LEONIDA_MOUSE_SENSITIVITY` (1, 0.1..10), `LEONIDA_MOUSE_INVERT_Y=1`,
`LEONIDA_MOUSE_DEADZONE` (0.24), `LEONIDA_MOUSE_CURVE` (0.6), `LEONIDA_MOUSE_LOOK=0` (off: the old behaviour, buttons
whenever the window has focus). Unit-tested (`mouse_look_turns_speed_into_a_stick_past_the_dead_zone`); the dead zone
and curve are first guesses at the title's own stick response, not measured.

## PlayStation pads and the active input of the D3D12 runtime

The D3D12 runtime has no SDL. Besides XInput it reads Sony pads (vendor `054C`: DualSense `0CE6`, DualSense Edge `0DF2`,
DualShock 4 `05C4`, `09CC`, USB adapter `0BA0`) over Windows HID directly (`gameinput/hid.rs`), on USB and Bluetooth,
written from the public report layouts (the Linux `hid-playstation` driver documents them). One thread per pad reads
input reports; a rescan every 2 s finds pads that came or went. A Bluetooth pad is moved to its full report by reading
calibration feature report `0x05`.

| | USB input | Bluetooth input | USB output | Bluetooth output |
|---|---|---|---|---|
| DualSense | `0x01`, 64 bytes, data from byte 1 | `0x31`, 78 bytes, data from byte 2 | `0x02`, 63 | `0x31`, 78, CRC-32 last |
| DualShock 4 | `0x01`, 64 bytes, data from byte 1 | `0x11`, data from byte 3 | `0x05`, 32 | `0x11`, 78, CRC-32 last |

Buttons: Cross, Circle, Square, Triangle are A, B, X, Y; L1/R1 the shoulders; L2/R2 the triggers (analog byte, the
digital bit is ignored); L3/R3 the stick clicks; Options is Menu; Create (Share) and the touchpad click are View;
the PS and mute buttons are not passed. Sticks are 0..255, centre 128. Rumble: the big motor of the title's
`SetRumbleState` goes to the pad's left motor, the small one to its right (`rumble_report`; on Bluetooth the CRC is
seeded with `0xA2`). Trigger effects and the lightbar are not driven. A Sony pad takes the first slot XInput leaves
empty (all pads are one pad for the title anyway, `LEONIDA_ONE_PAD`).

A pad that Steam Input or DS4Windows already shows through XInput is not read twice: when input comes on an XInput pad and
on a readable Sony pad within 150 ms of each other, they are one controller for the next 10 s, and the Sony pad's own
reading is left out of what the title sees. A Sony pad present but not openable (hidden by HidHide, held exclusively)
counts the same way: input on XInput is then PlayStation input.

**Active input.** `gameinput::active_family()` (`leonida-hle`, readable from any thread, lock-free) says which kind of
device was used last: `Family::Xbox`, `Family::PlayStation` or `Family::KeyboardMouse`; `family_generation()` goes up by one
with each change. It follows the rules of [Active input](#active-input) above (an edge counts, the first reading of a
device is its baseline), with the keyboard and mouse as a third family (a key going down, or mouse look pushing the
stick past 0.35). A switch is immediate: the first deliberate input of another family changes the answer, however long
the one before was in use; only the change after that one waits, `LEONIDA_PROMPTS_SWITCH_MS` = 300 ms from the switch,
so two devices used at once change it at most about three times a second. Before the first input it is what is
connected when the runtime first looks: PlayStation with a Sony pad, Xbox with any other pad, the keyboard and mouse
with no pad at all (a wireless pad still asleep counts as none: `LEONIDA_PROMPTS=xbox` is the way round it). One line
is logged on each change (`input in use: PlayStation (Sony pad input)`).
`LEONIDA_PROMPTS=xbox|playstation|keyboard|auto` forces it. The button prompts follow it at the title's one read of its
glyph movie: see [prompt_glyphs.md](prompt_glyphs.md). Unit-tested on hand-made report bytes and the family rules; not
run against a real pad yet.

## Rumble and triggers

`IGameInputDevice::SetRumbleState` takes four motor levels, 0..1. The two body motors go to `SDL_RumbleGamepad` on
every pad that has rumble. The two trigger motors depend on the pad:

- Xbox One and Series pads (and anything else SDL reports trigger rumble for): `SDL_RumbleGamepadTriggers`, the same
  impulse triggers as on console.
- DualSense: the trigger level becomes an adaptive-trigger effect sent with `SDL_SendGamepadEffect`, chosen by
  `LEONIDA_DS_TRIGGERS`.
- Others (DualShock 4, Switch Pro): the trigger levels are dropped and the device reports no trigger motors.

**This is an approximation.** The Xbox title only sends an impulse-trigger vibration level per frame. The PS5 version
of a game has effects authored per weapon and vehicle (weapon resistance, a click at a trigger position, and so on);
none of that exists in the Xbox build, so the shim can only turn the level it gets into a generic effect. Expect it to
feel like the Xbox signal played through the DualSense's trigger motors, not like the PS5 release.

The DualSense effect is SDL's 47-byte DualSense effects block (`DS5EffectsState_t` in SDL's `SDL_hidapi_ps5.c`, the
format `test/testcontroller.c` uses): byte 0 holds the valid flags `0x04 | 0x08` (right and left trigger effect),
bytes 10-20 the right trigger effect and bytes 21-31 the left one. The effect modes are the three SDL's test program
uses:

| `LEONIDA_DS_TRIGGERS` | level 0 | level > 0 |
|---|---|---|
| `rumble` (default) | `05` (effect off) | `06 <freq> <level*255> 00`: vibration at `LEONIDA_DS_TRIGGER_FREQ` Hz from the start of the pull |
| `resistance` | `05` | `01 00 <level*255>`: constant resistance over the whole pull |
| `off` | nothing is sent; the triggers stay as they are | |

An effect is sent only when its bytes change, so a steady level costs one report.

## Force feedback and haptics

`IGameInputDevice` reports the motors a pad really has, and drives them. There are two kinds, and they come from two
places:

| GameInput | comes from | the shim reports |
|---|---|---|
| `forceFeedbackMotorCount`, `forceFeedbackMotorInfo` | SDL opened the pad's joystick as a haptic device (`SDL_OpenHapticFromJoystick`), which it does for a wheel or a stick, never for a gamepad | one motor at index 0: `supportedAxes` LinearX, `maxSimultaneousEffects` SDL's limit, and one flag per effect kind from SDL's feature bits |
| `hapticFeedbackMotorCount`, `hapticFeedbackMotorInfo` | the trigger motors the pad already has for rumble: Xbox impulse triggers, or a DualSense with `LEONIDA_DS_TRIGGERS` on | two motors, left and right trigger, one waveform each |

A pad with neither keeps the answer the shim gave before this existed: no force-feedback or haptic motors,
`CreateForceFeedbackEffect` `E_INVALIDARG`, `IsForceFeedbackMotorPoweredOn` false, `SetHapticMotorState` `E_INVALIDARG`.
The keyboard pad is one of those, and so is any pad SDL opens as a gamepad only.

### Force feedback: `CreateForceFeedbackEffect`

`IGameInputForceFeedbackEffect` is the title's object; SDL is touched only on the poll thread. `SetParams`, `SetGain`
and `SetState` record the change and bump a version, and the next poll creates, updates, runs or stops the SDL effect,
so a title call still costs a lock and a copy. GameInput's eleven effect kinds are SDL's eleven force-feedback effects:

| GameInput kind | SDL type | fields |
|---|---|---|
| `Constant` | `SDL_HAPTIC_CONSTANT` | `level` = magnitude × gain |
| `Ramp` | `SDL_HAPTIC_RAMP` | `start` and `end` from the start and end magnitude |
| `SineWave`, `SquareWave`, `TriangleWave`, `SawtoothUpWave`, `SawtoothDownWave` | `SDL_HAPTIC_SINE`, `SQUARE`, `TRIANGLE`, `SAWTOOTHUP`, `SAWTOOTHDOWN` | `period` = 1000/frequency in ms, `magnitude`, `offset` = bias, `phase` = the effect's degrees × 100 |
| `Spring`, `Friction`, `Damper`, `Inertia` | `SDL_HAPTIC_SPRING`, `FRICTION`, `DAMPER`, `INERTIA` | positive and negative coefficient, saturation and dead zone on all three axes, `center` from the magnitude |

- Only the X magnitude is read, because the motor reports LinearX: the axis a wheel's or a stick's motor acts on. An
effect for another axis is played on this one, not dropped.
- `SetForceFeedbackMotorGain` is SDL's device gain (`SDL_SetHapticGain`, 0..100) and scales every effect on the motor;
`IGameInputForceFeedbackEffect::SetGain` scales that one effect's levels. Both are clamped to 0..1.
- The envelope: attack and release become SDL's `attack_length` and `fade_length` with the gains as their levels,
`sustainGain` scales the magnitude, attack + sustain + release is SDL's `length`, and `playCount` is the iteration count,
where 0 is "until stopped". No duration at all is a 60 s SDL length re-run every 20 s — the same refresh the rumble
motors get — so an effect with no end keeps playing without being restarted every poll. An effect that plays its
length reports `GameInputFeedbackStopped` afterwards.
- An all-zero envelope (what a title that only sets a magnitude leaves behind) means "no envelope", not silence, so
the effect plays at its own magnitude rather than at gain 0.
- A new effect starts `GameInputFeedbackRunning`: `CreateForceFeedbackEffect` already carried its parameters, and the
documented use — create once, `SetParams` per frame — never reaches `SetState`. `GameInputFeedbackPaused` stops the
SDL effect, because SDL pauses the device where GameInput pauses one effect.
- `LEONIDA_RUMBLE=0` stops every effect, like every other output path.
- The kind is checked against the motor's flags when the effect is created, so a kind the pad does not list is
`E_INVALIDARG`. SDL is not asked there — that is a title call — so if SDL still refuses an effect the poll thread sends
nothing for it rather than guessing.

### Haptics: `SetHapticMotorState`

The trigger motors play one waveform each: an intensity, which is the one thing SDL lets the shim send on a trigger,
through the same output as the trigger rumble — `SDL_RumbleGamepadTriggers`, or the DualSense effect block. `duration`
and `repeatDelay` are microseconds, `playCount` 0 plays until the state is set again, and a null `params` stops the
motor. For a waveform with a duration, each repetition plays for that duration and then leaves a quiet interval of
`repeatDelay` before the next repetition. The poll thread samples the current phase. During a pulse, the stronger of
the haptic intensity and ordinary trigger rumble wins. During the interval, ordinary trigger rumble continues.

**This is an approximation too, and a coarser one than the rumble.** A real haptic motor has a table of waveforms, each
with its own HID usage; SDL exposes no such table — a DualSense takes one effects block and everything else takes a
trigger impulse — so the shim reports a single waveform per motor (an intensity, usage 0x0F/0x58) instead of the pad's
real ones, and plays any request as an intensity. A title that picks waveform 3 by name cannot be served beyond
intensity 0; waveform indices other than 0 are `E_INVALIDARG`.

## Motion

Pads whose SDL gamepad reports both a gyroscope and an accelerometer (a DualSense, a Switch Pro, Steam Input pads) get
`GameInputKindMotion` in `supportedInput` and a `motionInfo` (`GameInputMotionInfo`, Microsoft's v0 layout); `IGameInputReading::GetMotionState`
returns a `GameInputMotionState` on their readings, and `GetCurrentReading`/`GetNextReading` answer a
`GameInputKindMotion` query for such a pad and return `GAMEINPUT_E_READING_NOT_FOUND` for a pad without sensors. A
reading callback registered for `GameInputKindMotion` hears only such pads: like a device callback, it is limited to
devices that support at least one of the kinds it names (Microsoft's `RegisterReadingCallback` reference). The
sensors are enabled when the pad is opened, at SDL's requested rate, and every poll reads the latest sample.

- The state carries **signed fractions of the maxima `motionInfo` reports** (1.0 = full magnitude), which is the
  convention Microsoft documents for `GameInputMotionState`. SDL delivers accel in m/s² (gravity included) and gyro
  in rad/s, so the shim divides by the maxima. The maxima are this shim's choice — SDL does not expose a sensor
  range — and are 2 g (19.6133 m/s²) and 2000 deg/s (34.9066 rad/s), a DualSense's accelerometer and gyro ranges
  (VERIFY against the game and a real pad).
- A pad at rest sits at about 0.5 on the gravity axis and 0.0 on all gyro axes. SDL answers sensor reads with zeros
  before the device's first sample arrives; since a real accelerometer never reads exactly zero (gravity), all-zero
  accel means "no sample yet" and the reading carries no motion at all — `GetMotionState` returns false.
- SDL's gamepad API has no compass and the shim synthesises no orientation quaternion, so the magnetic-field and
  orientation members are zero with `GameInputMotionAccuracyUnknown`.
- A pad with sensors streams a reading every ~8 ms (~125 Hz) even when nothing else changes, so motion is not stuck
  at the last button event; pads without sensors keep the old change-driven behaviour. The 8 ms window and the 512-
  reading history cap bound the cost.
- `gameinput_probe` prints the accel and gyro fractions when the pad has sensors (a resting pad shows ~0.5 g).

## Active input

The title is told that every pad is an Xbox One pad, so it cannot know what the player is holding. The shim keeps
that record itself, for the runtime's own use, such as button prompt glyphs that follow the device in use:
`rt::gameinput::active_input()` returns the family of the device used last, a generation that goes up by one with each
change, and whether `LEONIDA_PROMPTS` forced it. It needs no lock and can be read from any thread, every frame.

| SDL gamepad type | family |
|---|---|
| `PS5` (DualSense, DualSense Edge) | PlayStation 5 |
| `PS4` (DualShock 4) | PlayStation 4 |
| `PS3` (DualShock 3) | PlayStation 3 |
| `NINTENDO_SWITCH_PRO`, the Joy-Con types | Nintendo |
| the [keyboard pad](#keyboard-pad) | keyboard and mouse |
| everything else (Xbox One/Series, Xbox 360, generic, unknown) | Xbox |

SDL takes the type from the pad's vendor and product id. Only deliberate input changes the answer
(`runtime/src/active_input.h`, tested by `active_input_test` without SDL):

- an edge: a button going down (any of SDL's, the DualSense touchpad included), a trigger rising past 0.3, or a stick
  leaving a radius of 0.35. A held button, trigger or stick, stick drift inside the radius and analog noise never
  count. The mouse moves the keyboard pad's right stick, so a real mouse movement counts through the same rule and a
  jitter of a count or two does not;
- a pad's first reading after it connects is its baseline, so connecting a pad with a button held, or with a worn
  stick resting past the radius, changes nothing;
- after a change, the next one waits `LEONIDA_PROMPTS_SWITCH_MS` (300 ms by default). Input from another family inside
  that time is ignored, not queued, so two devices used at once cannot make the answer flicker;
- input from a second device of the family already in use changes nothing.

Before the first deliberate input the answer is Xbox. Each change logs one line, for example
`input in use: PlayStation 5 (DualSense Wireless Controller, button press)`. `LEONIDA_PROMPTS` forces a family (a
line is logged when it takes effect); tracking goes on underneath, so clearing it returns at once to the device in use.

## Environment variables

| variable | default | effect |
|---|---|---|
| `LEONIDA_DS_TRIGGERS` | `rumble` | DualSense trigger effects: `off`, `rumble` or `resistance` (above) |
| `LEONIDA_DS_TRIGGER_GAIN` | `1` | scales the trigger level before it becomes an effect, 0..4 |
| `LEONIDA_DS_TRIGGER_FREQ` | `30` | vibration frequency of the `rumble` mode, 1..255 |
| `LEONIDA_DS_LIGHTBAR` | unset | `RRGGBB` (hex) sets the DualSense/DualShock 4 lightbar when the pad connects; `off` turns it dark; unset keeps SDL's player colour |
| `LEONIDA_RUMBLE` | `1` | `0` turns all rumble, trigger and force-feedback output off |
| `LEONIDA_PROMPTS` | `auto` | forces the [active input](#active-input) family: `xbox`, `playstation` (or `ps5`), `ps4`, `ps3`, `nintendo` or `keyboard`; `auto` follows the devices |
| `LEONIDA_PROMPTS_SWITCH_MS` | `300` | shortest time between two changes of the active input family, 0..2000 ms |
| `LEONIDA_PROMPTS_LIVE` | `1` | `0` (or `off`) serves one family's glyph movie at the title's read instead of the live one that follows a switch during play ([prompt_glyphs.md](prompt_glyphs.md#following-a-device-switch-during-play)) |
| `LEONIDA_PROMPTS_PAD` | `playstation` | the pad half of the live movie when the keyboard is in use at the title's read: `xbox` serves the keyboard movie alone, as before |
| `LEONIDA_GAMEINPUT_THREAD` | `1` | `0` stops the background poll thread; only `rt::gameinput::poll()` then reads the pads (tests) |
| `LEONIDA_KEYBOARD_PAD` | `1` | the [keyboard pad](#keyboard-pad), read while this process has focus; `always` reads keys whatever has focus; `off` removes it |
| `LEONIDA_INPUT_SCRIPT` | unset | Comma-separated `button@seconds` entries, e.g. `a@2,a@4,start@6`. With SDL3 they drive the keyboard pad (on unless `LEONIDA_KEYBOARD_PAD=off`); without SDL3 they drive [one scripted pad](#scripted-input-without-sdl3), the only device. The first pad update (without SDL3, the first `GameInputCreate`) reads the script once at startup and starts the clock. `reload_config()` does not reread it. Each press lasts 300 ms, or `hold` seconds when the entry is `button@seconds:hold` (more than 0, at most 600). With SDL3 a press then stays down until the title has read the pads six times since it began, but never past 5 s from its start (or its hold, if longer). A title reads its pad once a frame, so at a few seconds a frame a 300 ms press can fall between two reads and never arrive: on the retail title's "Couldn't autosave" prompt, three 300 ms `b` presses did nothing, while 120 presses 0.5 s apart got through; one `b@1100:3` replaces them. Buttons are `a b x y start back lb rb up down left right`. Spaces around entries are allowed. Empty entries, unknown buttons, invalid times (including negative or non-finite values) and invalid holds (0 or less, more than 600, not a number) are counted and ignored. |
| `LEONIDA_MOUSE_SENSITIVITY` | `1` | scales how far the mouse moves the keyboard pad's right stick, 0.1..10 |

SDL's own hints (`SDL_JOYSTICK_*`, see SDL's `SDL_hints.h`) also apply, for example `SDL_JOYSTICK_HIDAPI_PS5=0` to
leave a DualSense to the generic driver, or `SDL_GAMECONTROLLERCONFIG` to add a mapping for an unknown pad.

## How it runs

One thread owns SDL: a background thread started by the first `GameInputCreate` that polls every 2 ms. It opens new
pads, closes removed ones, takes a reading of each, and applies rumble, haptic and force-feedback requests. Title calls
never touch SDL: they read the latest reading or leave a request, so a call costs a lock and a copy. Callbacks (device, reading, guide
button) run on that thread, as GameInput runs them on its own threads. Once the title creates a dispatcher
(`IGameInput::CreateDispatcher`), callbacks are queued instead, the dispatcher's wait handle is signalled, and
`IGameInputDispatcher::Dispatch` runs them on the title's thread, oldest first, within its quota: at least one queued
event per call (a quota of 0 runs exactly one), no further event once the quota has passed, and only the events
queued when the call started (later ones wait for the next call, so even an unlimited quota returns). The wait
handle is signalled again while events remain. An event is queued only when a registered callback wants it (a
reading with no reading callback, say, is no work), so readings nobody hears cannot build a backlog that a title
running one item a frame (`Dispatch(0)`) never catches up on, with a later pad's connect event stuck behind it. The
first few `RegisterDeviceCallback` calls (filter, kind, status filter, enumeration) and the first `CreateDispatcher`
and `Dispatch` calls are logged, since they decide how the title hears of a pad plugged in after start.

The API surface:

| interface | implemented | not implemented |
|---|---|---|
| `IGameInput` | `GetCurrentTimestamp` (µs), `GetCurrentReading`, `GetNextReading`, `GetPreviousReading`, `RegisterReadingCallback`, `RegisterDeviceCallback` (blocking and async enumeration), `RegisterGuideButtonCallback`, `RegisterKeyboardLayoutCallback` (never fires), `StopCallback`, `UnregisterCallback`, `CreateDispatcher`, `FindDeviceFromId`, `EnableOemDeviceSupport` (no-op), `SetFocusPolicy` (no-op) | `GetTemporalReading` (`E_NOTIMPL`, as in GameInput v0 itself; see below), `CreateAggregateDevice`, `FindDeviceFromObject/PlatformHandle/PlatformString` |
| `IGameInputReading` | kind, sequence number, timestamp, device, gamepad state, UI navigation state, controller axes and buttons, motion state, raw report (pads opened through HID, see [Raw HID](#raw-hid)) | keyboard, mouse, touch, arcade/flight stick, racing wheel (all return nothing) |
| `IGameInputDevice` | device info, status, battery, `SetRumbleState`, force-feedback motors with `CreateForceFeedbackEffect`/`IGameInputForceFeedbackEffect`, `IsForceFeedbackMotorPoweredOn`, `SetForceFeedbackMotorGain`, haptic trigger motors with `SetHapticMotorState`, `CreateRawDeviceReport`, `GetRawDeviceFeature`, `SetRawDeviceFeature`, `SendRawDeviceOutput` (pads opened through HID) | `SendRawDeviceOutputWithResponse`, `ExecuteRawDeviceIoControl`, exclusive raw access, power off, input synchronization (no-ops) |
| `IGameInputRawDeviceReport` | device, report info (kind, id, size), raw data size, get and set raw data | item values (`Get/Set/ResetItemValue`, `ResetAllItems` answer false: no item tables) |
| `IGameInputDispatcher` | `Dispatch` (with its quota), `OpenWaitHandle` | |

`CreateAggregateDevice` takes exactly one of the keyboard, mouse, gamepad, arcade stick, flight stick or racing wheel
kinds (none, several, or another kind is `E_INVALIDARG`) and returns one device per kind, the same object on every
call: family `GameInputFamilyAggregate`, always connected, with that kind as its `supportedInput`, and a fixed
`deviceId` per kind that `FindDeviceFromId` also answers. Readings asked
through it (`GetCurrentReading`, `GetNextReading`, `GetPreviousReading`) come from every connected device of that
kind (`GetCurrentReading` answers the most recent of them); asking it for another kind is
`GAMEINPUT_E_READING_NOT_FOUND`. A reading or device callback registered with an aggregate device as its filter is
refused with `E_NOTIMPL` and an invalid token.

A device object stays alive for the whole process. When a pad is unplugged its status drops to
`GameInputDeviceNoStatus` and its device callback runs; when the same pad is plugged in again (matched by SDL GUID and
serial or device path) the title gets the same object back, connected again.

## Raw HID

A title can read a pad's raw HID input reports and send it output and feature reports (RT-175). The shim opens each
pad's HID device through SDL's hidapi (`SDL_hid_*`), by the device path SDL reports for the pad. When that path is not
a HID path, it falls back to the pad's vendor and product id, but only when exactly one game-pad collection (usage page
1, usage 5) has them, so twins never mix. It reads the report descriptor to find every input, output and feature
report: its id (0 when the descriptor declares none) and its payload size in bytes, without the id byte.

A pad opened this way gets the following:

- `GameInputKindRawDeviceReport` in `supportedInput` and `GameInputDeviceRawIoEnabled` in its status.
- `inputReportInfo`, `outputReportInfo` and `featureReportInfo` tables with their counts. Every report has `itemCount`
  0: the descriptor's items (usages, logical ranges, units) are not decoded.
- Readings that carry the newest raw input report. Each poll drains the reports that arrived, the last declared one
  wins, and a report with new bytes makes a reading of its own. Before the first report, a reading carries none.
- These device calls, each on any `IGameInputRawDeviceReport` of the right kind whose id the pad declares:
  - `CreateRawDeviceReport(id, kind)` makes a zeroed report.
  - `GetRawDeviceFeature(id)` reads a feature report.
  - `SetRawDeviceFeature` sends one.
  - `SendRawDeviceOutput` writes an output report.

  An undeclared id or kind is `E_INVALIDARG`, and a failed transfer `E_FAIL`.

`SetRawData` takes a buffer of exactly the report's size and refuses any other size, so a report is never half old and
half new. The item calls answer false. `SendRawDeviceOutputWithResponse`, `ExecuteRawDeviceIoControl` and exclusive
access still return `E_NOTIMPL` / false.

A pad without such a HID device keeps the old answers: no raw kind, no tables, `E_NOTIMPL` from the raw calls.

- **Xbox pads on Windows** are read by SDL through XInput (path `XInput#n`). SDL's hidapi skips their XInput HID
  interface (`&IG_` in the path), noting that it carries no full HID reports. So they have no raw I/O here, and the log
  says so.
- **SDL virtual joysticks and the keyboard pad** have no path, so no HID device either.
- **Pads SDL reads through hidapi** can have raw I/O: DualSense, DualShock 4, Switch Pro, and most others in DirectInput
  mode.

`rt::gameinput::set_hid_backend` replaces the hidapi backend (tests). `rt::gameinput::parse_report_descriptor` is the
descriptor walk: main items Input, Output and Feature add Report Size × Report Count bits to the current Report ID, Push
and Pop save and restore the globals, and long items are skipped. It refuses a truncated item, Report ID 0 or above
255, a Pop without a Push, and a report over 64 KiB.

## Reading history

Each pad keeps the readings the poll took for it, one per change it saw, so `GetNextReading` and `GetPreviousReading`
can step through input the title has not read yet, such as a button pressed and released between two of its frames.
A reading leaves the history once the reading after it is more than 500 ms old, so the current state stays reachable
however long the pad then idles. A pad keeps at most 512 readings, and none once it is unplugged. A reading the title
holds stays valid after it leaves the history.

- With a device the search covers that pad; with none, every connected pad. Readings of different pads are ordered by
  when the shim took them, not by timestamp, since pads polled together share one.
- `GetNextReading` returns the first reading after the reference, `GetPreviousReading` the last one before it.
- The horizon is the newest reading dropped from the histories searched (with no device, the reference's pad counts
  too, even unplugged). A step that would cross it fails rather than skip input.

| situation | result |
|---|---|
| output null; reference null | `E_POINTER`; `E_INVALIDARG` |
| no supported kind in the mask | `GAMEINPUT_E_READING_NOT_FOUND` |
| the device given is unplugged | `GAMEINPUT_E_DEVICE_DISCONNECTED` |
| next: the horizon is after the reference; previous: it is not before it | `GAMEINPUT_E_REFERENCE_READING_TOO_OLD` |
| nothing newer, or nothing older after the horizon | `GAMEINPUT_E_READING_NOT_FOUND` |

After a pad is plugged back in, its last reading before the unplug leads to the reconnect snapshot, older ones are
`REFERENCE_READING_TOO_OLD`, and sequence numbers carry on. Each poll drains SDL's gamepad button and axis events.
For each connected pad, events with the same SDL timestamp form one sample. Intermediate samples reach the history
and reading or Guide callbacks, while the final reading uses the current pad snapshot. GameInput timestamps still
record when the shim polled. A short press is recoverable when the SDL backend reports its two edges with distinct timestamps.

### Device identity

`AppLocalDeviceId` is the SDL GUID in bytes 0-15 and an FNV-1a hash of the serial or path in bytes 16-31. Pads that
SDL cannot tell apart, such as two of the same model with no serial and no path, would share that id, and
`FindDeviceFromId` would return the first for both. They are twins: the first keeps the id, so a single pad's id is
unchanged, and each further one gets an id hashed from its twin number (`t:<n>:` before the serial or path). A new id
is checked against every device seen in the process and moved to the next number if taken, so no two devices share
one. A pad that comes back takes the lowest-numbered disconnected twin's object and id; a connected device is never
reused.

That is assignment by order, not identification. With one twin unplugged, the right object comes back if the same pad
returns, but another identical pad plugged in instead gets it too. With two or more unplugged, nothing tells them
apart: if they return in a different order, the objects and ids are swapped between the physical pads, and the shim
cannot detect it. The same sequence of plugs gives the same ids in every run, since the ids depend only on the GUID,
the serial or path and the order; for pads already connected at start, that order is SDL's (see [VERIFY](#verify)).

## ABI

`runtime/shims/gameinput_abi.h` declares the v0 GameInput API as Leonida's own code: the interfaces in vtable order,
the enums the shim uses and the structs it has to lay out. It was written against Microsoft's public v0 header (the
GDK version, also published as the `Microsoft.GameInput` NuGet package 0.2303.22621.3038). The header is not in the
repository. Its struct offsets were checked by compiling both side by side with `offsetof` asserts for every field the
shim fills (`GameInputDeviceInfo` 320 bytes with `deviceFamily` at 96 and the info pointers from 160,
`GameInputGamepadState` 28 bytes, and the rest in `gameinput_abi.h`). Four structs had only their size compared, or
were taken as empty, and were wrong: `GameInputControllerAxisInfo` (48 bytes) and `GameInputControllerButtonInfo` (32)
have a `GameInputLabel` at offset 4, in what would otherwise be padding, so the members behind it sat four bytes early,
and `GameInputGamepadInfo` and `GameInputUiNavigationInfo` are tables of 14 and 21 labels (56 and 84 bytes). Every
member of the four now compares equal side by side, and `gameinput_abi.h` pins each offset. The host's GameInput 0.2309
fills the two tables in that order: a DualSense (`054c:0ce6`) over USB has the cross, circle, square and triangle icons
for A, B, X and Y, `Menu`, `View`, `Up`/`Down`/`Left`/`Right`, `L1`/`R1` and `L3`/`R3`, and null axis and button arrays.
The shim gives every control the Xbox label of its position on every pad, because every pad is presented as an Xbox
One pad; an Xbox pad's labels on the host are not measured.

The force-feedback and haptic declarations (`GameInputForceFeedbackMotorInfo`, `GameInputHapticWaveformInfo`,
`GameInputHapticFeedbackMotorInfo`, the envelope and parameter structs, `IGameInputForceFeedbackEffect`) were
transcribed from that header's public source and pinned with the same kind of `static_assert` on their sizes and
fields — they were not compiled against it, since it is not in the repository. That is the one place the shim's ABI
rests on a transcription rather than on a side-by-side compile.

## Tests

- `active_input_test` (CTest, no SDL): the [active input](#active-input) tracker's rules on synthetic samples with
  its own clock. `gameinput_test` runs them on a DualSense, a DualShock 4 (Sony `054c:09cc`), an Xbox pad and the
  keyboard pad: no change when pads connect (one with a button held) or a held button is let go, each family by a
  button, the touchpad, a trigger or a stick, stick drift and a one-count mouse jitter ignored, a real mouse movement
  counted, the 300 ms window on the real clock, and `LEONIDA_PROMPTS` forcing, changing, ignoring an unknown value
  and clearing.
- `gameinput_no_sdl_test` (CTest, only in a build without SDL3, no controller): `gameinput_no_sdl` checks the
  identity-only object (both names served, `AddRef`/`Release`, `E_NOTIMPL` without touching the out-parameter).
  `gameinput_no_sdl_script` sets `LEONIDA_INPUT_SCRIPT` with overlapping presses, a mixed-case name, `rsup` and three
  rejected entries, puts the shim on a fake clock and checks the scripted pad: blocking, async and dispatcher
  enumeration (and none without enumeration, for another status or another kind), the device info, `FindDeviceFromId`,
  the buttons, UI navigation and right stick read at chosen times (held for 0.3 s, a later press of the same button
  not cut short, nothing after the script), no new reading without a change, `GetPreviousReading` and
  `GetNextReading`, no motion, and reading callbacks answering `E_NOTIMPL`.
- `gameinput_test` (CTest, no controller): turns SDL's real backends off and drives the shim through
  `rt::shims::find` with SDL virtual joysticks, an Xbox-style pad with trigger motors, a DualSense (Sony
  `054c:0ce6`) and a pad without trigger motors. It checks enumeration and device callbacks, the button, stick,
  trigger and UI-navigation mapping, reading callbacks and sequence numbers, the reading history (a button and trigger
  tapped between two shim polls, both directions, two pads interleaved and filtered by device, ageing out, held readings, unplug and
  replug), the guide button, motor and trigger
  rumble as SDL receives them, the DualSense effect bytes in each `LEONIDA_DS_TRIGGERS` mode, the lightbar, a
  dispatcher and its quota, async and blocking enumeration, unregistering, unplugging and replugging, and three identical pads
  (an id each, `FindDeviceFromId` and device-filtered readings per pad, replugging one, two and all three, and the
  first twin's id equal to the single-pad id). Motion runs on a virtual pad with sensors (`nsensors` in the
  virtual-joystick description, fed with `SDL_SendJoystickVirtualSensorData`): the kind and `motionInfo` on a sensor
  pad and not on a plain one, no motion before the first sample, normalisation against the `motionInfo` maxima, the
  accuracy values, the ±1 clamp, the ~8 ms cadence, that a motion query on a pad without sensors is
  `GAMEINPUT_E_READING_NOT_FOUND`, and that a Motion reading callback hears only the sensor pad. The keyboard pad is
  driven through `rt::gameinput::set_keyboard_source` and `set_cursor_source` with fake keys, focus and cursor: every
  binding, two keys at once, each WASD direction, opposite keys cancelling, diagonals, the mouse moving the right
  stick, clamping and decaying to 0, the mouse-button triggers, no input out of focus, release of buttons, sticks and
  triggers on focus loss, the `always` mode, and turning it off and on again.
  Raw HID (RT-175) is tested in two ways:
  - `parse_report_descriptor` runs on synthetic descriptors: report ids, none, Push/Pop, a long item, and the refused
    forms.
  - A fake backend (`set_hid_backend`) stands behind a virtual pad with pid.codes test ids. The test checks the report
    tables, the kind and status bits, a reading's raw report (newest declared id, without the id byte, an undeclared id
    ignored), creating, sending and reading back output and feature reports with their id byte, `SetRawData`'s exact
    size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, and the HID device closing on unplug.
- `gameinput_probe [--seconds N] [--rumble] [--force-feedback]` (by hand, with a pad connected): lists the pads with
  each one's raw HID report tables (or why it has none), plays each motor and trigger for a second with `--rumble`,
  holds a constant force at magnitude 1.0 on motor 0 for a second with `--force-feedback` (skipped, with the reason
  printed, on a pad the shim reports no force-feedback motor for), and prints whether SDL created that effect and is
  running it, separately from GameInput accepting it, then prints the live reading and the newest raw input report.

On hardware so far, with `gameinput_probe` and SDL 3.4.20 on Windows 11: a DualSense (`054c:0ce6`) over USB. It
connects as player 1 with trigger effects and gyro (`motors=0xf forcefeedback=0 haptic=2`). Pressed one at a time,
each of the 14 gamepad buttons set the one bit of the name [Mapping](#mapping) gives it: Cross, Circle, Square and Triangle
as `A`, `B`, `X` and `Y`, the d-pad, L1/R1, L3/R3, Create as `View` and Options as `Menu`. Both triggers reached
1.00 and both sticks -1.00 and +1.00 on each axis. At rest the accelerometer read about 0.5 on one axis and the gyro
0.0; shaking the pad by hand reached 1.00 on the accelerometer. With `--rumble` (the default `rumble` trigger mode)
and `LEONIDA_DS_LIGHTBAR=00ff00`, the person holding the pad reported the motors, the trigger effects and the lightbar
as working; nothing measured them, and the `resistance` mode was not tried.
    size, the item calls, `E_INVALIDARG` / `E_FAIL` / `E_NOTIMPL`, the HID device closing on unplug, and a held
    reading's `GetRawReport` waiting while a reconnect rebuilds the report tables.
- `gameinput_probe [--seconds N] [--rumble]` (by hand, with a pad connected): lists the pads with each one's raw HID
  report tables (or why it has none), plays each motor and trigger for a second with `--rumble`, then prints the live
  reading and the newest raw input report.

## VERIFY

These need the game executable or a test on hardware:

- **Which API version and module.** The shim is GameInput v0 and registers `GameInputCreate` under `gameinput.dll`
  and `xgameruntime.dll`. GameInput v1 and later (NuGet 1.x and up) changed the interfaces; if the executable was
  built against one of those, the vtables need a second set.
- **IIDs.** `QueryInterface` answers the v0 IIDs from the public header.
- **Reading history.** Microsoft's [next reading](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/interfaces/igameinput/methods/igameinput_getnextreading)
  and [previous reading](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/interfaces/igameinput/methods/igameinput_getpreviousreading) pages describe half a second of readings per device and failure when old readings leave the stream. The table above records the shim's HRESULT choices.
  `GetTemporalReading` returns `E_NOTIMPL` with a null reading on purpose: Microsoft's
  [reference page](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/input/gameinput/deprecated/interfaces/igameinput/methods/igameinput_gettemporalreading)
  says it "was never implemented in v0" and returns `E_NOTIMPL`, and v1 removed it. The v0 header (NuGet
  `Microsoft.GameInput` 0.2303.22621.3038) declares it as `(timestamp, device, reading)`, the layout the shim has;
  the page's five-parameter form does not match that header.
- **UI navigation mapping** and the **controller-axis convention** (0..1 with sticks at 0.5) are this shim's choice,
  not measured from a console.
- **Battery capacity** is reported as a fraction (remaining 0..1 of full 1), not in device units.
- **`UnregisterCallback` timeout** is not honoured; it waits for a callback that is running.
- **Motion normalisation maxima** (2 g accel, 2000 deg/s gyro) are this shim's choice; SDL exposes no sensor range,
  and whether the game reads motion, and against what scale, is unknown until it runs. The accelerometer range a
  DualSense exposes can also be wider than 2 g, so hard shakes may clamp at 1.0: a hand shake of a real DualSense
  did reach 1.00 on one axis.
- **Motion members the shim does not provide** (magnetic field, orientation) are zero with
  `GameInputMotionAccuracyUnknown`; whether a title wants a synthesised quaternion there is unknown.
- **Device family**: every pad is reported as `GameInputFamilyXboxOne`; a title that filters on family sees only
  that.
- **Active input behind Steam Input**: when Steam turns a PlayStation pad into a virtual Xbox pad, SDL may report the
  virtual one's type, and the active input then says Xbox; `LEONIDA_PROMPTS` is the way round it until that is
  checked on a real setup.
- **Identical pads at start**: twins are numbered in the order the shim opens them. For pads already connected when
  it starts, that is SDL's enumeration order, not measured on Windows for identical pads; if it varies between runs,
  so does which pad gets which id.
- **Raw mouse registration**: Windows keeps one raw-input target window per device type and process, so if the title
  registers raw mouse input itself (a console title is not expected to), it replaces the shim's registration and the
  right stick falls back to nothing. The shim does not detect that yet.
- **Keyboard pad as a second pad**: it is one more connected gamepad, so with a controller plugged in the title sees
  two. A title that follows only the first pad it saw, or asks the player to press a button to pick the active pad,
  may ignore one of them; whether the game does either is unknown.
- **Mouse on the right stick**: the scale (1024 units per pixel per poll) and decay (7/8 per poll) are a starting
  point, not tuned in game. The title adds its own stick acceleration and deadzone on top, so aiming may feel slow
  near center or jumpy.
- **Force feedback on hardware**: which pads SDL opens as haptic devices on Windows (a DirectInput wheel or stick,
  not an Xbox pad) and how many force-feedback motors a title would really see there. The shim reports one motor with
  LinearX; whether a wheel wants a second axis, or LinearY for a stick, is unknown until one is attached.
  `gameinput_probe` prints `forcefeedback=` and `haptic=` per pad.
- **How a force-feedback effect feels**: the magnitudes go out 1:1 (SDL's -32767..32767 from GameInput's -1..1) with
  no scaling beyond the two gains. Whether a game's curb weight, road texture and crash feel right, and whether
  `SDL_SetHapticGain` is the right place for a motor's master gain on the driver SDL picks, needs a wheel in game.
- **Envelope and phase units**: GameInput's `phase` is read as degrees (SDL takes hundredths of a degree) and its
  durations as microseconds summed into SDL's `length`. Neither came from a measurement, only from the header's
  remarks.
- **A new effect starting stopped or running**: the shim starts it running, because the documented use creates an
  effect once and only ever calls `SetParams`. A title that creates one and waits for `SetState` would play a frame
  early; whether this one does is unknown until it runs.
- **Haptic waveforms**: the single intensity waveform (usage 0x0F/0x58) is this shim's choice, not the pad's table, so
  a title that asks for a particular waveform gets intensity-only behaviour. Whether the game uses haptic motors at
  all — as opposed to `SetRumbleState` — is unknown.
- **Raw HID on a real pad**: the synthetic tests, the XInput refusal and one DualSense over USB have run.
  - What ran: an Xbox Series X controller over Bluetooth on Windows 11 connects and plays normally, with no raw I/O,
    and the log names the reason.
  - What ran: a DualSense (`054c:0ce6`) over USB on Windows 11 through `gameinput_probe`. Its descriptor gives 1
    input report (id 1, 63 bytes), 1 output report (id 2, 47 bytes) and 20 feature reports, and the raw input report
    changed on every reading (2,442 distinct reports in a 40 s capture). No output or feature report was sent
    through the raw calls.
  - Still to confirm: a DualSense over Bluetooth, a DualShock 4 or a Switch Pro through `gameinput_probe`, which
    should print the descriptor's reports and changing raw input bytes.
  - Size convention: report sizes exclude the id byte, and `GetRawData` returns the payload without it. What
    Microsoft's runtime does for a device with report ids is not documented on the reference pages.
  - Readings: a pad that streams reports makes a reading for each changed one, like the runtime's
    `GameInputKindRawDeviceReport` stream, but whether the title asks for raw reports at all is unknown.