upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authoraslan2142 <jan.trencansky@protonmail.com>2026-11-25 14:15:49 +0100
committerGitHub <noreply@github.com>2026-11-25 14:15:49 +0100
commit384abe5b06d08e349f4b4e4394c68f036da47dc7 (patch)
tree6e608825aba65b0cad8776badce77ee58a31e67c /runtime
parent98c2f7777276f83eb90b491a51721ef90a43ea73 (diff)
parentc68f494160c8e79c76bfa109b2e99571a5c11358 (diff)
Merge pull request #1843 from aslan2142/rt-input-script-no-sdl3
RT-INPUT-SCRIPT-NO-SDL3: scripted input in builds without SDL3
Diffstat (limited to 'runtime')
-rw-r--r--runtime/CMakeLists.txt5
-rw-r--r--runtime/README.md8
-rw-r--r--runtime/shims/gameinput.cpp171
-rw-r--r--runtime/shims/gameinput_no_sdl.cpp644
-rw-r--r--runtime/shims/gameinput_no_sdl.h12
-rw-r--r--runtime/shims/gameinput_script.h180
-rw-r--r--runtime/test/gameinput_no_sdl_test.cpp242
7 files changed, 1122 insertions, 140 deletions
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index e9cb8d434..57ccce76a 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -690,7 +690,8 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
690 endif() 690 endif()
691 if(NOT (LEONIDA_SDL3 AND TARGET SDL3::SDL3-static)) 691 if(NOT (LEONIDA_SDL3 AND TARGET SDL3::SDL3-static))
692 # Nothing served gameinput.dll in a build without SDL3, so the loader fell through to the host's gameinput.dll and 692 # Nothing served gameinput.dll in a build without SDL3, so the loader fell through to the host's gameinput.dll and
693 # that one answers GameInputCreate with a null interface the title dereferences. Keep the object identity honest. 693 # that one answers GameInputCreate with a null interface the title dereferences. Keep the object identity honest,
694 # and with LEONIDA_INPUT_SCRIPT serve one pad driven by the script (shims/gameinput_script.h, shared with SDL3's).
694 target_sources(gta6rt PRIVATE shims/gameinput_no_sdl.cpp) 695 target_sources(gta6rt PRIVATE shims/gameinput_no_sdl.cpp)
695 add_executable(gameinput_no_sdl_test 696 add_executable(gameinput_no_sdl_test
696 test/gameinput_no_sdl_test.cpp 697 test/gameinput_no_sdl_test.cpp
@@ -1657,6 +1658,8 @@ if(BUILD_TESTING)
1657 add_test(NAME active_input COMMAND active_input_test) 1658 add_test(NAME active_input COMMAND active_input_test)
1658 if(WIN32 AND TARGET gameinput_no_sdl_test) 1659 if(WIN32 AND TARGET gameinput_no_sdl_test)
1659 add_test(NAME gameinput_no_sdl COMMAND gameinput_no_sdl_test) 1660 add_test(NAME gameinput_no_sdl COMMAND gameinput_no_sdl_test)
1661 # LEONIDA_INPUT_SCRIPT without SDL3: the scripted pad, its device callbacks and its readings on a fake clock.
1662 add_test(NAME gameinput_no_sdl_script COMMAND gameinput_no_sdl_test --input-script)
1660 endif() 1663 endif()
1661 if(WIN32 AND TARGET gameinput_test) 1664 if(WIN32 AND TARGET gameinput_test)
1662 add_test(NAME gameinput COMMAND gameinput_test) 1665 add_test(NAME gameinput COMMAND gameinput_test)
diff --git a/runtime/README.md b/runtime/README.md
index 1573b8883..070fa28ad 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -288,7 +288,9 @@ Current limits, by design:
288 lightbar. Optional and CMake-only: built when an installed SDL3 is found, 288 lightbar. Optional and CMake-only: built when an installed SDL3 is found,
289 or with `-DLEONIDA_SDL3_FETCH=ON` to download the pinned release; nothing is downloaded otherwise, and the 289 or with `-DLEONIDA_SDL3_FETCH=ON` to download the pinned release; nothing is downloaded otherwise, and the
290 `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is 290 `scripts/build_runtime.ps1` cl.exe fallback never builds it. See [docs/gameinput.md](../docs/gameinput.md) for the mapping, the `LEONIDA_DS_*` settings and what is
291 unverified. 291 unverified. A build without SDL3 links `shims/gameinput_no_sdl.cpp` instead: no devices, or with
292 `LEONIDA_INPUT_SCRIPT` set one scripted pad driven by the script alone, so a headless or CI build can get past the
293 title's first prompt ([docs/gameinput.md](../docs/gameinput.md#scripted-input-without-sdl3)).
292 294
293### What `xgameruntime.dll` reports: environment overrides 295### What `xgameruntime.dll` reports: environment overrides
294 296
@@ -340,6 +342,7 @@ ones marked *diagnostic* only add log lines or exist to compare a run with and w
340| `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. | 342| `LEONIDA_VOLUME_MIPS` | on | The XG layout of a 3D texture with mips or a block format is computed (`shims/xg_xs_layout.h`). `0` refuses it. |
341| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only in the build the watchdog was measured in. | 343| `LEONIDA_TITLE_WATCHDOG` | unset (armed) | The title's own hang watchdog stays armed by default, as on the console: if the game's main loop does not report for 30 seconds, the title ends itself. `0` makes `gta6rt --run` keep it from firing while the game thread waits for the driver, for example on the first boot after a driver update (`src/main.cpp`), and only in the build the watchdog was measured in. |
342| `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. | 344| `LEONIDA_PEEK_SECONDS` | `10` | *Diagnostic.* The period of the `LEONIDA_PEEK` thread (`src/main.cpp`), which prints 8-byte values of the title's image. |
345| `LEONIDA_INPUT_SCRIPT` | unset | Timed pad presses, `button@seconds` separated by commas (`a@70,a@85,start@120`), each held 300 ms; the clock starts with the shim. Works with and without SDL3: with SDL3 it drives the keyboard pad (`LEONIDA_KEYBOARD_PAD=always`), without SDL3 one scripted pad that is the only device. Controllers and the keyboard pad still need SDL3. Format and buttons in [docs/gameinput.md](../docs/gameinput.md#environment-variables). |
343| `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. | 346| `LEONIDA_INPUT_LOG` | on | The GameInput shim logs every press in `LEONIDA_INPUT_SCRIPT`'s form (`name@seconds`), so a session played by hand can be replayed. `0` turns the lines off. |
344| `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). | 347| `LEONIDA_LOG_ALLOCINFO` | unset | *Diagnostic.* `1` logs every device slot 25 call (`GetResourceAllocationInfo`) with its thread, description and sizes (`shims/d3d12_xs_device.cpp`). |
345| `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. | 348| `LEONIDA_LOG_EXE_PIPELINES` | unset | *Diagnostic.* When set, one line per distinct graphics pipeline that uses a program translated from the executable's inline containers. |
@@ -454,6 +457,9 @@ SDK, or `-DLEONIDA_VULKAN_HEADERS_FETCH=ON` to download the pinned Khronos Vulka
454 457
455`gameinput_test` (only with SDL3; otherwise CTest lists `gameinput` as not run) drives the GameInput shim on SDL virtual joysticks (no controller needed): enumeration, readings 458`gameinput_test` (only with SDL3; otherwise CTest lists `gameinput` as not run) drives the GameInput shim on SDL virtual joysticks (no controller needed): enumeration, readings
456and the button/axis mapping, rumble and trigger rumble, DualSense effect bytes, a dispatcher, and hot-plug. 459and the button/axis mapping, rumble and trigger rumble, DualSense effect bytes, a dispatcher, and hot-plug.
460`gameinput_no_sdl_test` (only without SDL3) checks the shim a build without SDL3 links: `gameinput_no_sdl` the
461identity-only object, `gameinput_no_sdl_script` the scripted pad of `LEONIDA_INPUT_SCRIPT` on a fake clock (device
462callbacks, readings at chosen times, the reading history).
457`gameinput_probe [--seconds N] [--rumble] [--force-feedback]` is the manual check on a real pad: it prints live 463`gameinput_probe [--seconds N] [--rumble] [--force-feedback]` is the manual check on a real pad: it prints live
458readings, plays each motor and trigger, and holds a constant force on a pad that reports a force-feedback motor. 464readings, plays each motor and trigger, and holds a constant force on a pad that reports a force-feedback motor.
459 465
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index db685e71f..47e9aa941 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -52,6 +52,7 @@
52 52
53#include "gameinput.h" 53#include "gameinput.h"
54#include "gameinput_abi.h" 54#include "gameinput_abi.h"
55#include "gameinput_script.h"
55#include "shims.h" 56#include "shims.h"
56 57
57using namespace gi; 58using namespace gi;
@@ -132,18 +133,30 @@ const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); }
132 133
133// ---- configuration ---------------------------------------------------------------------------------------------- 134// ---- configuration ----------------------------------------------------------------------------------------------
134 135
135std::string env(const char* name) { 136std::string env(const char* name) { return rt::gameinput::script::env_lower(name); }
136 // Any length: an input script (LEONIDA_INPUT_SCRIPT) is easily longer than a fixed buffer, and a value that did 137
137 // not fit used to read as unset. 138// The script's button numbers are SDL's (gameinput_script.h shares them with the shim built without SDL3).
138 const DWORD need = GetEnvironmentVariableA(name, nullptr, 0); // with the terminator 139constexpr bool script_buttons_match_sdl() {
139 if (need == 0) return {}; 140 const struct {
140 std::string s(need, '\0'); 141 uint32_t bit;
141 const DWORD n = GetEnvironmentVariableA(name, s.data(), need); 142 SDL_GamepadButton sdl;
142 if (n == 0 || n >= need) return {}; 143 } expected[] = {{GameInputGamepadA, SDL_GAMEPAD_BUTTON_SOUTH}, {GameInputGamepadB, SDL_GAMEPAD_BUTTON_EAST},
143 s.resize(n); 144 {GameInputGamepadX, SDL_GAMEPAD_BUTTON_WEST}, {GameInputGamepadY, SDL_GAMEPAD_BUTTON_NORTH},
144 for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c))); 145 {GameInputGamepadMenu, SDL_GAMEPAD_BUTTON_START}, {GameInputGamepadView, SDL_GAMEPAD_BUTTON_BACK},
145 return s; 146 {GameInputGamepadLeftShoulder, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER},
147 {GameInputGamepadRightShoulder, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
148 {GameInputGamepadDPadUp, SDL_GAMEPAD_BUTTON_DPAD_UP}, {GameInputGamepadDPadDown, SDL_GAMEPAD_BUTTON_DPAD_DOWN},
149 {GameInputGamepadDPadLeft, SDL_GAMEPAD_BUTTON_DPAD_LEFT},
150 {GameInputGamepadDPadRight, SDL_GAMEPAD_BUTTON_DPAD_RIGHT}};
151 if (std::size(expected) != std::size(rt::gameinput::script::kButtons)) return false;
152 for (const auto& e : expected) {
153 bool found = false;
154 for (const auto& b : rt::gameinput::script::kButtons) found |= b.bit == e.bit && b.sdl == e.sdl;
155 if (!found) return false;
156 }
157 return true;
146} 158}
159static_assert(script_buttons_match_sdl(), "gameinput_script.h's SDL button numbers drifted from SDL_GamepadButton");
147 160
148rt::gameinput::Config read_config() { 161rt::gameinput::Config read_config() {
149 rt::gameinput::Config c; 162 rt::gameinput::Config c;
@@ -1103,30 +1116,7 @@ Snapshot read_pad(Device* d) {
1103 } 1116 }
1104 } 1117 }
1105 1118
1106 // UI navigation derived from the gamepad (VERIFY against the console's own mapping). 1119 s.ui = rt::gameinput::script::ui_navigation(s.gamepad);
1107 const uint32_t b = s.gamepad.buttons;
1108 const float t = 0.5f;
1109 uint32_t& u = s.ui;
1110 if (b & GameInputGamepadMenu) u |= GameInputUiNavigationMenu;
1111 if (b & GameInputGamepadView) u |= GameInputUiNavigationView;
1112 if (b & GameInputGamepadA) u |= GameInputUiNavigationAccept;
1113 if (b & GameInputGamepadB) u |= GameInputUiNavigationCancel;
1114 if (b & GameInputGamepadX) u |= GameInputUiNavigationContext1;
1115 if (b & GameInputGamepadY) u |= GameInputUiNavigationContext2;
1116 if (b & GameInputGamepadLeftThumbstick) u |= GameInputUiNavigationContext3;
1117 if (b & GameInputGamepadRightThumbstick) u |= GameInputUiNavigationContext4;
1118 if ((b & GameInputGamepadDPadUp) || s.gamepad.leftThumbstickY > t) u |= GameInputUiNavigationUp;
1119 if ((b & GameInputGamepadDPadDown) || s.gamepad.leftThumbstickY < -t) u |= GameInputUiNavigationDown;
1120 if ((b & GameInputGamepadDPadLeft) || s.gamepad.leftThumbstickX < -t) u |= GameInputUiNavigationLeft;
1121 if ((b & GameInputGamepadDPadRight) || s.gamepad.leftThumbstickX > t) u |= GameInputUiNavigationRight;
1122 if (b & GameInputGamepadLeftShoulder) u |= GameInputUiNavigationPageLeft;
1123 if (b & GameInputGamepadRightShoulder) u |= GameInputUiNavigationPageRight;
1124 if (s.gamepad.leftTrigger > t) u |= GameInputUiNavigationPageUp;
1125 if (s.gamepad.rightTrigger > t) u |= GameInputUiNavigationPageDown;
1126 if (s.gamepad.rightThumbstickY > t) u |= GameInputUiNavigationScrollUp;
1127 if (s.gamepad.rightThumbstickY < -t) u |= GameInputUiNavigationScrollDown;
1128 if (s.gamepad.rightThumbstickX < -t) u |= GameInputUiNavigationScrollLeft;
1129 if (s.gamepad.rightThumbstickX > t) u |= GameInputUiNavigationScrollRight;
1130 return s; 1120 return s;
1131} 1121}
1132 1122
@@ -1897,80 +1887,29 @@ void update_keyboard_pad() {
1897 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); 1887 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]);
1898 // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard 1888 // LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120" (with LEONIDA_KEYBOARD_PAD=always): timed presses on the keyboard
1899 // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt 1889 // pad, in seconds since the pad's first update, each held 300 ms. For unattended boots: the title's first prompt
1900 // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). Buttons: a b x y start back lb rb 1890 // waits for a button with no timeout (docs/re/notes/firstframe.md, step 5). The parser, the timeline and the
1901 // up down left right. The rsup and rsdown entries replay the right-stick throws logged below. 1891 // button names are gameinput_script.h's, shared with the scripted pad of a build without SDL3.
1892 namespace script = rt::gameinput::script;
1902 int right_y = g_keyboard.right_y; 1893 int right_y = g_keyboard.right_y;
1903 struct ScriptedPress { 1894 static const script::Script scripted = [] {
1904 SDL_GamepadButton button; 1895 script::Script s = script::parse(env("LEONIDA_INPUT_SCRIPT"));
1905 double at; 1896 if (!s.empty() || s.rejected)
1906 int right_y = 0; 1897 std::fprintf(stderr, "[rt] gameinput: LEONIDA_INPUT_SCRIPT: %zu scripted press(es), %zu rejected\n",
1907 }; 1898 s.presses.size(), s.rejected);
1908 static const std::vector<ScriptedPress> script = [] { 1899 return s;
1909 std::vector<ScriptedPress> out;
1910 static const std::pair<const char*, SDL_GamepadButton> names[] = {
1911 {"a", SDL_GAMEPAD_BUTTON_SOUTH}, {"b", SDL_GAMEPAD_BUTTON_EAST},
1912 {"x", SDL_GAMEPAD_BUTTON_WEST}, {"y", SDL_GAMEPAD_BUTTON_NORTH},
1913 {"start", SDL_GAMEPAD_BUTTON_START}, {"back", SDL_GAMEPAD_BUTTON_BACK},
1914 {"lb", SDL_GAMEPAD_BUTTON_LEFT_SHOULDER}, {"rb", SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER},
1915 {"up", SDL_GAMEPAD_BUTTON_DPAD_UP}, {"down", SDL_GAMEPAD_BUTTON_DPAD_DOWN},
1916 {"left", SDL_GAMEPAD_BUTTON_DPAD_LEFT}, {"right", SDL_GAMEPAD_BUTTON_DPAD_RIGHT}};
1917 const std::string text = env("LEONIDA_INPUT_SCRIPT");
1918 if (text.empty()) return out;
1919 constexpr char whitespace[] = " \t\r\n\f\v";
1920 size_t items = 0;
1921 for (size_t at = 0, end; at <= text.size(); at = end + 1) {
1922 ++items;
1923 end = std::min(text.find(',', at), text.size());
1924 const std::string item = text.substr(at, end - at);
1925 const size_t first = item.find_first_not_of(whitespace);
1926 const size_t sep = item.find('@');
1927 if (sep == std::string::npos || first >= sep) continue;
1928 const char* time = item.c_str() + sep + 1;
1929 char* tail;
1930 const double seconds = std::strtod(time, &tail);
1931 if (tail == time || !std::isfinite(seconds) || seconds < 0 ||
1932 item.find_first_not_of(whitespace, tail - item.c_str()) != std::string::npos) continue;
1933 if (item.compare(first, sep - first, "rsup") == 0 || item.compare(first, sep - first, "rsdown") == 0) {
1934 const bool up = item.compare(first, sep - first, "rsup") == 0;
1935 out.push_back({SDL_GAMEPAD_BUTTON_INVALID, seconds, up ? -kStickFull : kStickFull});
1936 continue;
1937 }
1938 for (const auto& [name, button] : names) {
1939 if (item.compare(first, sep - first, name) == 0) {
1940 out.push_back({button, seconds});
1941 break;
1942 }
1943 }
1944 }
1945 std::fprintf(stderr, "[rt] gameinput: LEONIDA_INPUT_SCRIPT: %zu scripted press(es), %zu rejected\n",
1946 out.size(), items - out.size());
1947 return out;
1948 }(); 1900 }();
1949 if (!script.empty()) { 1901 if (!scripted.empty()) {
1950 static const ULONGLONG origin = GetTickCount64(); 1902 static const ULONGLONG origin = GetTickCount64();
1951 const double now = (GetTickCount64() - origin) / 1000.0; 1903 const double now = (GetTickCount64() - origin) / 1000.0;
1952 // One decision per button: a later entry for the same button must not release what an earlier entry holds 1904 const script::Held held = script::held_at(scripted, now);
1953 // (it did: with several entries only the last one ever reached the title). 1905 if (held.stick) right_y = held.stick > 0 ? -kStickFull : kStickFull; // SDL's +Y is down
1954 bool scripted[SDL_GAMEPAD_BUTTON_COUNT] = {}; 1906 for (const script::Button& b : script::kButtons) {
1955 bool named[SDL_GAMEPAD_BUTTON_COUNT] = {}; 1907 if (!(scripted.named & b.bit)) continue;
1956 for (const auto& press : script) { 1908 const auto button = static_cast<SDL_GamepadButton>(b.sdl);
1957 const bool held = now >= press.at && now < press.at + 0.3; 1909 SDL_SetJoystickVirtualButton(g_keyboard.js, button, (held.buttons & b.bit) || down[button]);
1958 if (press.right_y) {
1959 if (held) right_y = press.right_y;
1960 } else {
1961 named[press.button] = true;
1962 scripted[press.button] |= held;
1963 }
1964 }
1965 for (int button = 0; button < SDL_GAMEPAD_BUTTON_COUNT; ++button) {
1966 if (!named[button]) continue;
1967 SDL_SetJoystickVirtualButton(g_keyboard.js, static_cast<SDL_GamepadButton>(button),
1968 scripted[button] || down[button]);
1969 static bool was[SDL_GAMEPAD_BUTTON_COUNT] = {};
1970 if (scripted[button] && !was[button])
1971 std::fprintf(stderr, "[rt] gameinput: scripted press of button %d at %.1f s\n", button, now);
1972 was[button] = scripted[button];
1973 } 1910 }
1911 static uint32_t was = 0;
1912 script::log_scripted(held.buttons, &was, now);
1974 } 1913 }
1975 const int reach = lx && ly ? kStickDiagonal : kStickFull; 1914 const int reach = lx && ly ? kStickDiagonal : kStickFull;
1976 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach)); 1915 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach));
@@ -2053,26 +1992,10 @@ void poll_once() {
2053 { 1992 {
2054 static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0"; 1993 static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0";
2055 static const ULONGLONG log_origin = GetTickCount64(); 1994 static const ULONGLONG log_origin = GetTickCount64();
2056 if (log_presses) { 1995 if (log_presses)
2057 static const std::pair<uint32_t, const char*> kNames[] = { 1996 rt::gameinput::script::log_presses(snap.gamepad.buttons & ~d->last_snap.gamepad.buttons,
2058 {GameInputGamepadA, "a"}, {GameInputGamepadB, "b"}, 1997 d->last_snap.gamepad.rightThumbstickY, snap.gamepad.rightThumbstickY,
2059 {GameInputGamepadX, "x"}, {GameInputGamepadY, "y"}, 1998 (GetTickCount64() - log_origin) / 1000.0, d->name.c_str());
2060 {GameInputGamepadMenu, "start"}, {GameInputGamepadView, "back"},
2061 {GameInputGamepadLeftShoulder, "lb"}, {GameInputGamepadRightShoulder, "rb"},
2062 {GameInputGamepadDPadUp, "up"}, {GameInputGamepadDPadDown, "down"},
2063 {GameInputGamepadDPadLeft, "left"}, {GameInputGamepadDPadRight, "right"}};
2064 const double at = (GetTickCount64() - log_origin) / 1000.0;
2065 const uint32_t pressed = snap.gamepad.buttons & ~d->last_snap.gamepad.buttons;
2066 for (const auto& n : kNames)
2067 if (pressed & n.first)
2068 std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", n.second, at, d->name.c_str());
2069 const auto throw_of = [](float y) { return y > 0.6f ? 1 : y < -0.6f ? -1 : 0; };
2070 const int was = throw_of(d->last_snap.gamepad.rightThumbstickY);
2071 const int is = throw_of(snap.gamepad.rightThumbstickY);
2072 if (is != was && is != 0)
2073 std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", is > 0 ? "rsup" : "rsdown", at,
2074 d->name.c_str());
2075 }
2076 } 1999 }
2077 d->last_snap = snap; 2000 d->last_snap = snap;
2078 // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button 2001 // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button
diff --git a/runtime/shims/gameinput_no_sdl.cpp b/runtime/shims/gameinput_no_sdl.cpp
index ab190d250..77b7ebccf 100644
--- a/runtime/shims/gameinput_no_sdl.cpp
+++ b/runtime/shims/gameinput_no_sdl.cpp
@@ -5,21 +5,47 @@
5// one), and that host answers GameInputCreate with a null interface while the title ignores the HRESULT: the title's 5// one), and that host answers GameInputCreate with a null interface while the title ignores the HRESULT: the title's
6// lazy singleton stores the null and calls AddRef/Release through it, which is a page fault at address 0. 6// lazy singleton stores the null and calls AddRef/Release through it, which is a page fault at address 0.
7// 7//
8// This file keeps the object identity honest without any input backend: one static object, slot 0/1/2 as 8// This file serves one of two objects, chosen on the first GameInputCreate:
9// QueryInterface/AddRef/Release, E_NOTIMPL for every other slot, so a caller that only holds and releases the 9//
10// interface survives and one that asks for devices gets a clean refusal instead of a null dereference. 10// - LEONIDA_INPUT_SCRIPT unset: an object that keeps the identity honest without any input backend. One static
11// object, slot 0/1/2 as QueryInterface/AddRef/Release, E_NOTIMPL for every other slot, so a caller that only
12// holds and releases the interface survives and one that asks for devices gets a clean refusal instead of a null
13// dereference.
14// - LEONIDA_INPUT_SCRIPT set: one scripted pad, driven only by the script (gameinput_script.h, the same parser and
15// timeline the SDL3 shim's keyboard pad uses). Without it a build without SDL3 has no device at all and the
16// title waits at its first "press A" prompt forever. The pad is an Xbox One gamepad that is connected from the
17// first GameInputCreate on: device enumeration through RegisterDeviceCallback (blocking, async, and through a
18// dispatcher), GetCurrentReading, GetNextReading and GetPreviousReading, and readings whose GetGamepadState and
19// GetUiNavigationState follow the script. A reading is taken when the title asks for one, so no thread runs;
20// reading callbacks, aggregate devices, rumble and every other device still need SDL3. Controllers and the
21// keyboard pad need SDL3 too.
11#include <windows.h> 22#include <windows.h>
12 23
24#include <algorithm>
13#include <array> 25#include <array>
14#include <atomic> 26#include <atomic>
15#include <cstdint> 27#include <cstdint>
16#include <cstdio> 28#include <cstdio>
29#include <cstring>
30#include <deque>
31#include <mutex>
32#include <string>
33#include <thread>
17#include <utility> 34#include <utility>
35#include <vector>
18 36
37#include "gameinput_abi.h"
38#include "gameinput_no_sdl.h"
39#include "gameinput_script.h"
19#include "shims.h" 40#include "shims.h"
20 41
42using namespace gi;
43namespace script = rt::gameinput::script;
44
21namespace { 45namespace {
22 46
47// ---- no script: the identity-only object ------------------------------------------------------------------------
48
23constexpr size_t kSlots = 64; // comfortably covers the public v0 IGameInput vtable 49constexpr size_t kSlots = 64; // comfortably covers the public v0 IGameInput vtable
24 50
25struct GameInputStub { 51struct GameInputStub {
@@ -66,8 +92,616 @@ ULONG __stdcall stub_add_ref(GameInputStub*) { return g_refs.fetch_add(1) + 1; }
66 92
67ULONG __stdcall stub_release(GameInputStub*) { return g_refs.fetch_sub(1) - 1; } 93ULONG __stdcall stub_release(GameInputStub*) { return g_refs.fetch_sub(1) - 1; }
68 94
95// ---- LEONIDA_INPUT_SCRIPT: the scripted pad ---------------------------------------------------------------------
96
97constexpr uint32_t kKinds =
98 GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation;
99constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled;
100constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT, as the SDL3 shim reports them
101constexpr uint32_t kButtonCount = 15; // SDL's standard gamepad buttons, numbered as the script's Button::sdl
102constexpr size_t kHistoryCap = 64; // readings kept for GetNextReading/GetPreviousReading; one per change
103constexpr char kPadName[] = "Scripted pad (Leonida)";
104
105uint64_t qpc_now_us() {
106 static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }();
107 LARGE_INTEGER c;
108 QueryPerformanceCounter(&c);
109 return static_cast<uint64_t>(c.QuadPart / freq.QuadPart * 1'000'000 + c.QuadPart % freq.QuadPart * 1'000'000 / freq.QuadPart);
110}
111std::atomic<rt::gameinput_no_sdl::ClockFn> g_clock{&qpc_now_us};
112uint64_t now_us() { return g_clock.load()(); }
113
114bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; }
115
116ULONG release_floor(std::atomic<ULONG>& refs) { // objects kept for the process: never freed
117 ULONG r = refs.load();
118 while (r > 1 && !refs.compare_exchange_weak(r, r - 1)) {}
119 return r > 1 ? r - 1 : 1;
120}
121
122template <size_t Slot>
123void not_served(const char* what) {
124 static std::atomic<bool> warned{false};
125 if (!warned.exchange(true, std::memory_order_relaxed))
126 std::fprintf(stderr, "[rt] gameinput: slot %zu (%s) is not served without SDL3; E_NOTIMPL (logged once)\n",
127 Slot, what);
128}
129
130class Pad;
131Pad& pad();
132
133class Reading final : public IGameInputReading {
134public:
135 Reading(const GameInputGamepadState& state, uint64_t seq, uint64_t ts) : state_(state), seq_(seq), ts_(ts) {}
136
137 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
138 if (!out) return E_POINTER;
139 if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputReading)) {
140 AddRef();
141 *out = static_cast<IGameInputReading*>(this);
142 return S_OK;
143 }
144 *out = nullptr;
145 return E_NOINTERFACE;
146 }
147 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
148 ULONG STDMETHODCALLTYPE Release() override {
149 const ULONG r = --refs_;
150 if (r == 0) delete this;
151 return r;
152 }
153
154 uint32_t STDMETHODCALLTYPE GetInputKind() override { return kKinds; }
155 uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; }
156 uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; }
157 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override;
158 bool STDMETHODCALLTYPE GetRawReport(void** report) override {
159 if (report) *report = nullptr;
160 return false;
161 }
162 uint32_t STDMETHODCALLTYPE GetControllerAxisCount() override { return kAxisCount; }
163 uint32_t STDMETHODCALLTYPE GetControllerAxisState(uint32_t count, float* out) override {
164 if (!out) return 0;
165 // 0..1 with 0.5 at rest for the sticks, as the SDL3 shim reports them.
166 const float axes[kAxisCount] = {(state_.leftThumbstickX + 1) * 0.5f, (state_.leftThumbstickY + 1) * 0.5f,
167 (state_.rightThumbstickX + 1) * 0.5f, (state_.rightThumbstickY + 1) * 0.5f,
168 state_.leftTrigger, state_.rightTrigger};
169 const uint32_t n = std::min(count, kAxisCount);
170 std::memcpy(out, axes, n * sizeof(float));
171 return n;
172 }
173 uint32_t STDMETHODCALLTYPE GetControllerButtonCount() override { return kButtonCount; }
174 uint32_t STDMETHODCALLTYPE GetControllerButtonState(uint32_t count, bool* out) override {
175 if (!out) return 0;
176 bool buttons[kButtonCount] = {};
177 for (const script::Button& b : script::kButtons) buttons[b.sdl] = (state_.buttons & b.bit) != 0;
178 const uint32_t n = std::min(count, kButtonCount);
179 std::memcpy(out, buttons, n * sizeof(bool));
180 return n;
181 }
182 uint32_t STDMETHODCALLTYPE GetControllerSwitchCount() override { return 0; }
183 uint32_t STDMETHODCALLTYPE GetControllerSwitchState(uint32_t, GameInputSwitchPosition*) override { return 0; }
184 uint32_t STDMETHODCALLTYPE GetKeyCount() override { return 0; }
185 uint32_t STDMETHODCALLTYPE GetKeyState(uint32_t, void*) override { return 0; }
186 bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; }
187 uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; }
188 uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; }
189 bool STDMETHODCALLTYPE GetMotionState(void*) override { return false; }
190 bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; }
191 bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; }
192 bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override {
193 if (!state) return false;
194 *state = state_;
195 return true;
196 }
197 bool STDMETHODCALLTYPE GetRacingWheelState(void*) override { return false; }
198 bool STDMETHODCALLTYPE GetUiNavigationState(GameInputUiNavigationState* state) override {
199 if (!state) return false;
200 state->buttons = script::ui_navigation(state_);
201 return true;
202 }
203
204 const GameInputGamepadState& state() const { return state_; }
205 uint64_t seq() const { return seq_; }
206
207private:
208 std::atomic<ULONG> refs_{1};
209 GameInputGamepadState state_;
210 uint64_t seq_, ts_;
211};
212
213// The one device. It lives for the process and is connected from the first GameInputCreate on.
214class Pad final : public IGameInputDevice {
215public:
216 Pad() {
217 GameInputDeviceInfo& i = info_;
218 i.infoSize = sizeof(GameInputDeviceInfo);
219 i.usage = {0x01, 0x05}; // HID generic desktop / game pad
220 std::memcpy(i.deviceId.value, "LEONIDA_SCRIPTED_PAD_DEVICE_ID\0\0", sizeof i.deviceId.value);
221 i.deviceRootId = i.deviceId;
222 i.deviceFamily = GameInputFamilyXboxOne; // every pad is an Xbox One pad to the title, as in the SDL3 shim
223 i.supportedInput = kKinds;
224 i.controllerAxisCount = kAxisCount;
225 i.controllerButtonCount = kButtonCount;
226 for (uint32_t a = 0; a < kAxisCount; ++a) {
227 axis_info_[a].mappedInputKinds = GameInputKindGamepad;
228 axis_info_[a].isContinuous = true;
229 axis_info_[a].hasRestValue = true;
230 axis_info_[a].restValue = a < 4 ? 0.5f : 0.0f;
231 axis_info_[a].resolution = 65536;
232 axis_info_[a].legacyHidIndex = axis_info_[a].legacyDInputIndex = static_cast<uint16_t>(a);
233 }
234 axis_info_[4].label = GameInputLabelXboxLeftTrigger;
235 axis_info_[5].label = GameInputLabelXboxRightTrigger;
236 const GameInputLabel labels[kButtonCount] = {
237 GameInputLabelXboxA, GameInputLabelXboxB, GameInputLabelXboxX,
238 GameInputLabelXboxY, GameInputLabelXboxView, GameInputLabelXboxGuide,
239 GameInputLabelXboxMenu, GameInputLabelXboxLeftStickButton, GameInputLabelXboxRightStickButton,
240 GameInputLabelXboxLeftShoulder, GameInputLabelXboxRightShoulder, GameInputLabelXboxDPadUp,
241 GameInputLabelXboxDPadDown, GameInputLabelXboxDPadLeft, GameInputLabelXboxDPadRight};
242 for (uint32_t b = 0; b < kButtonCount; ++b) {
243 button_info_[b].mappedInputKinds = GameInputKindGamepad;
244 button_info_[b].label = labels[b];
245 button_info_[b].legacyHidIndex = button_info_[b].legacyDInputIndex = static_cast<uint16_t>(b);
246 }
247 gamepad_info_ = {GameInputLabelXboxMenu, GameInputLabelXboxView, GameInputLabelXboxA,
248 GameInputLabelXboxB, GameInputLabelXboxX, GameInputLabelXboxY,
249 GameInputLabelXboxDPadUp, GameInputLabelXboxDPadDown, GameInputLabelXboxDPadLeft,
250 GameInputLabelXboxDPadRight, GameInputLabelXboxLeftShoulder, GameInputLabelXboxRightShoulder,
251 GameInputLabelXboxLeftStickButton, GameInputLabelXboxRightStickButton};
252 const GameInputLabel none = GameInputLabelNone;
253 ui_info_ = {GameInputLabelXboxMenu, GameInputLabelXboxView, GameInputLabelXboxA,
254 GameInputLabelXboxB, GameInputLabelXboxDPadUp, GameInputLabelXboxDPadDown,
255 GameInputLabelXboxDPadLeft, GameInputLabelXboxDPadRight, GameInputLabelXboxX,
256 GameInputLabelXboxY, GameInputLabelXboxLeftStickButton, GameInputLabelXboxRightStickButton,
257 GameInputLabelXboxLeftTrigger, GameInputLabelXboxRightTrigger, GameInputLabelXboxLeftShoulder,
258 GameInputLabelXboxRightShoulder, none, none, none, none, GameInputLabelXboxGuide};
259 i.controllerAxisInfo = axis_info_;
260 i.controllerButtonInfo = button_info_;
261 i.gamepadInfo = &gamepad_info_;
262 i.uiNavigationInfo = &ui_info_;
263 constexpr uint32_t name_size = sizeof kPadName - 1;
264 display_name_ = {name_size, name_size, kPadName};
265 i.displayName = &display_name_;
266 }
267
268 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
269 if (!out) return E_POINTER;
270 if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDevice)) {
271 AddRef();
272 *out = static_cast<IGameInputDevice*>(this);
273 return S_OK;
274 }
275 *out = nullptr;
276 return E_NOINTERFACE;
277 }
278 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
279 ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); }
280
281 const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info_; }
282 uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return kConnectedStatus; }
283 void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override {
284 if (state) *state = {0, 0, 0, 0, GameInputBatteryUnknown};
285 }
286 // No motors: the pad reports none, so every motor index is out of range.
287 HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t, const void*, void** effect) override {
288 if (effect) *effect = nullptr;
289 return E_INVALIDARG;
290 }
291 bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t) override { return false; }
292 void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t, float) override {}
293 HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t, const void*) override { return E_INVALIDARG; }
294 void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams*) override {}
295 void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {}
296 void STDMETHODCALLTYPE SendInputSynchronizationHint() override {}
297 void STDMETHODCALLTYPE PowerOff() override {}
298 HRESULT STDMETHODCALLTYPE CreateRawDeviceReport(uint32_t, int32_t, void** report) override { return no_raw(report); }
299 HRESULT STDMETHODCALLTYPE GetRawDeviceFeature(uint32_t, void** report) override { return no_raw(report); }
300 HRESULT STDMETHODCALLTYPE SetRawDeviceFeature(void*) override { return E_NOTIMPL; }
301 HRESULT STDMETHODCALLTYPE SendRawDeviceOutput(void*) override { return E_NOTIMPL; }
302 HRESULT STDMETHODCALLTYPE SendRawDeviceOutputWithResponse(void*, void** response) override { return no_raw(response); }
303 HRESULT STDMETHODCALLTYPE ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* size) override {
304 if (size) *size = 0;
305 return E_NOTIMPL;
306 }
307 bool STDMETHODCALLTYPE AcquireExclusiveRawDeviceAccess(uint64_t) override { return false; }
308 void STDMETHODCALLTYPE ReleaseExclusiveRawDeviceAccess() override {}
309
310private:
311 static HRESULT no_raw(void** out) {
312 if (out) *out = nullptr;
313 return E_NOTIMPL;
314 }
315 std::atomic<ULONG> refs_{1};
316 GameInputDeviceInfo info_{};
317 GameInputControllerAxisInfo axis_info_[kAxisCount]{};
318 GameInputControllerButtonInfo button_info_[kButtonCount]{};
319 GameInputGamepadInfo gamepad_info_{};
320 GameInputUiNavigationInfo ui_info_{};
321 GameInputString display_name_{};
322};
323
324Pad& pad() {
325 static Pad* p = new Pad;
326 return *p;
327}
328
329void Reading::GetDevice(IGameInputDevice** device) {
330 if (!device) return;
331 pad().AddRef();
332 *device = &pad();
333}
334
335enum class CbType { Device, Guide, KeyboardLayout };
336
337struct Callback {
338 GameInputCallbackToken token;
339 CbType type;
340 void* context;
341 void* fn;
342 bool active;
343};
344
345// A device callback's enumeration report that is delivered later (async enumeration), by a one-shot thread or, when
346// the title made a dispatcher, by IGameInputDispatcher::Dispatch on the title's thread.
347struct Pending {
348 GameInputCallbackToken token;
349 uint64_t timestamp;
350};
351
352struct State {
353 std::recursive_mutex mu; // everything below
354 std::recursive_mutex deliver_mu; // held while callbacks run; UnregisterCallback waits on it
355 std::atomic<DWORD> delivering_thread{0};
356 script::Script script;
357 uint64_t origin_us = 0; // the script's clock starts at the first GameInputCreate
358 bool log_presses = true; // LEONIDA_INPUT_LOG
359 uint32_t logged_held = 0; // what log_scripted saw last
360 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading
361 uint64_t evicted_seq = 0; // sequence number of the newest reading dropped from history
362 uint64_t seq = 0;
363 std::vector<Callback> callbacks;
364 std::vector<Pending> pending;
365 GameInputCallbackToken next_token = 1;
366 int dispatchers = 0;
367 HANDLE wait_event = nullptr; // auto-reset, signalled when a dispatcher has work
368};
369
370State& g() {
371 static State* s = new State; // never destroyed: a title thread may still read during exit
372 return *s;
373}
374
375// Takes a reading when the script's state at `now` differs from the current one. Under g().mu.
376void update(uint64_t now) {
377 State& s = g();
378 const double seconds = now > s.origin_us ? (now - s.origin_us) / 1e6 : 0.0;
379 const script::Held held = script::held_at(s.script, seconds);
380 GameInputGamepadState state{};
381 state.buttons = held.buttons;
382 state.rightThumbstickY = static_cast<float>(held.stick);
383 const Reading* last = s.history.empty() ? nullptr : s.history.back();
384 if (last && last->state().buttons == state.buttons && last->state().rightThumbstickY == state.rightThumbstickY)
385 return;
386 script::log_scripted(held.buttons, &s.logged_held, seconds);
387 if (s.log_presses && last)
388 script::log_presses(state.buttons & ~last->state().buttons, last->state().rightThumbstickY,
389 state.rightThumbstickY, seconds, kPadName);
390 s.history.push_back(new Reading(state, ++s.seq, now));
391 while (s.history.size() > kHistoryCap) {
392 s.evicted_seq = s.history.front()->seq();
393 s.history.front()->Release();
394 s.history.pop_front();
395 }
396}
397
398void call_device(const Callback& c, uint64_t timestamp) {
399 reinterpret_cast<GameInputDeviceCallback>(c.fn)(c.token, c.context, &pad(), timestamp, kConnectedStatus,
400 GameInputDeviceNoStatus);
401}
402
403// Runs the pending enumeration reports on the calling thread, without holding the state lock.
404void deliver() {
405 State& s = g();
406 std::lock_guard dl(s.deliver_mu);
407 std::vector<Pending> batch;
408 {
409 std::lock_guard lock(s.mu);
410 batch.swap(s.pending);
411 }
412 s.delivering_thread = GetCurrentThreadId();
413 for (const Pending& p : batch) {
414 Callback target{};
415 {
416 std::lock_guard lock(s.mu);
417 for (const Callback& c : s.callbacks)
418 if (c.token == p.token && c.active) target = c;
419 }
420 if (target.fn) call_device(target, p.timestamp);
421 }
422 s.delivering_thread = 0;
423}
424
425// Async enumeration: the report arrives after RegisterDeviceCallback returns, as GameInput delivers it from a thread
426// of its own; with a dispatcher, the title's Dispatch delivers it instead.
427void schedule_delivery() {
428 State& s = g();
429 {
430 std::lock_guard lock(s.mu);
431 if (s.dispatchers > 0) {
432 SetEvent(s.wait_event);
433 return;
434 }
435 }
436 std::thread([] {
437 {
438 std::lock_guard lock(g().mu);
439 if (g().dispatchers > 0) { // a dispatcher appeared meanwhile: it owns the delivery
440 SetEvent(g().wait_event);
441 return;
442 }
443 }
444 deliver();
445 }).detach();
446}
447
448class Dispatcher final : public IGameInputDispatcher {
449public:
450 Dispatcher() {
451 std::lock_guard lock(g().mu);
452 ++g().dispatchers;
453 if (!g().pending.empty()) SetEvent(g().wait_event);
454 }
455 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
456 if (!out) return E_POINTER;
457 if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputDispatcher)) {
458 AddRef();
459 *out = static_cast<IGameInputDispatcher*>(this);
460 return S_OK;
461 }
462 *out = nullptr;
463 return E_NOINTERFACE;
464 }
465 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
466 ULONG STDMETHODCALLTYPE Release() override {
467 const ULONG r = --refs_;
468 if (r == 0) {
469 {
470 std::lock_guard lock(g().mu);
471 --g().dispatchers;
472 }
473 delete this;
474 }
475 return r;
476 }
477 // The pending reports are few (one per async enumeration), so all of them run whatever the quota.
478 bool STDMETHODCALLTYPE Dispatch(uint64_t) override {
479 deliver();
480 std::lock_guard lock(g().mu);
481 return !g().pending.empty();
482 }
483 HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override {
484 if (!handle) return E_POINTER;
485 *handle = nullptr;
486 if (!DuplicateHandle(GetCurrentProcess(), g().wait_event, GetCurrentProcess(), handle, 0, FALSE,
487 DUPLICATE_SAME_ACCESS))
488 return HRESULT_FROM_WIN32(GetLastError());
489 return S_OK;
490 }
491
492private:
493 std::atomic<ULONG> refs_{1};
494};
495
496// GetNextReading (forward) and GetPreviousReading: the reading right after or right before the reference. A step
497// across a reading dropped from the history is REFERENCE_READING_TOO_OLD, as in the SDL3 shim.
498HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputReading** out, bool forward) {
499 if (!out) return E_POINTER;
500 *out = nullptr;
501 if (!ref) return E_INVALIDARG;
502 if (kind != GameInputKindUnknown && !(kind & kKinds)) return GAMEINPUT_E_READING_NOT_FOUND;
503 State& s = g();
504 std::lock_guard lock(s.mu);
505 update(now_us());
506 const uint64_t r = static_cast<Reading*>(ref)->seq();
507 if (forward ? s.evicted_seq > r : s.evicted_seq >= r) return GAMEINPUT_E_REFERENCE_READING_TOO_OLD;
508 Reading* best = nullptr;
509 for (Reading* c : s.history) {
510 if (forward && c->seq() > r) {
511 best = c;
512 break;
513 }
514 if (!forward && c->seq() < r) best = c;
515 }
516 if (!best) return GAMEINPUT_E_READING_NOT_FOUND;
517 best->AddRef();
518 *out = best;
519 return S_OK;
520}
521
522bool is_pad(IGameInputDevice* device) { return device == static_cast<IGameInputDevice*>(&pad()); }
523
524class ScriptedInput final : public IGameInput {
525public:
526 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override {
527 if (!out) return E_POINTER;
528 if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInput)) {
529 AddRef();
530 *out = static_cast<IGameInput*>(this);
531 return S_OK;
532 }
533 *out = nullptr;
534 return E_NOINTERFACE;
535 }
536 ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; }
537 ULONG STDMETHODCALLTYPE Release() override { return release_floor(refs_); } // a process-wide singleton
538
539 uint64_t STDMETHODCALLTYPE GetCurrentTimestamp() override { return now_us(); }
540
541 HRESULT STDMETHODCALLTYPE GetCurrentReading(uint32_t kind, IGameInputDevice* device, IGameInputReading** out) override {
542 if (!out) return E_POINTER;
543 *out = nullptr;
544 if (kind != GameInputKindUnknown && !(kind & kKinds)) return GAMEINPUT_E_READING_NOT_FOUND;
545 if (device && !is_pad(device)) return GAMEINPUT_E_DEVICE_NOT_FOUND;
546 State& s = g();
547 std::lock_guard lock(s.mu);
548 update(now_us());
549 Reading* r = s.history.back();
550 r->AddRef();
551 *out = r;
552 return S_OK;
553 }
554 HRESULT STDMETHODCALLTYPE GetNextReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device,
555 IGameInputReading** out) override {
556 if (device && !is_pad(device)) return out ? (*out = nullptr, GAMEINPUT_E_DEVICE_NOT_FOUND) : E_POINTER;
557 return find_reading(ref, kind, out, true);
558 }
559 HRESULT STDMETHODCALLTYPE GetPreviousReading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* device,
560 IGameInputReading** out) override {
561 if (device && !is_pad(device)) return out ? (*out = nullptr, GAMEINPUT_E_DEVICE_NOT_FOUND) : E_POINTER;
562 return find_reading(ref, kind, out, false);
563 }
564 // GameInput v0's own answer (see the SDL3 shim).
565 HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t, IGameInputDevice*, IGameInputReading** out) override {
566 if (!out) return E_POINTER;
567 *out = nullptr;
568 return E_NOTIMPL;
569 }
570 // Readings are taken when the title asks for one, so there is nothing to call back with.
571 HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice*, uint32_t, float, void*, GameInputReadingCallback,
572 GameInputCallbackToken* token) override {
573 if (token) *token = kInvalidCallbackToken;
574 not_served<8>("RegisterReadingCallback");
575 return E_NOTIMPL;
576 }
577
578 HRESULT STDMETHODCALLTYPE RegisterDeviceCallback(IGameInputDevice* device, uint32_t kind, uint32_t status_filter,
579 GameInputEnumerationKind enumeration, void* context,
580 GameInputDeviceCallback fn, GameInputCallbackToken* token) override {
581 if (token) *token = kInvalidCallbackToken;
582 if (!fn) return E_INVALIDARG;
583 State& s = g();
584 Callback c{0, CbType::Device, context, reinterpret_cast<void*>(fn), true};
585 // The pad is connected already, so only an enumeration reports it: there is no later connection event.
586 const bool report = enumeration != GameInputNoEnumeration && (!device || is_pad(device)) &&
587 (kind == GameInputKindUnknown || (kind & kKinds)) && (kConnectedStatus & status_filter);
588 bool later = false;
589 {
590 std::lock_guard lock(s.mu);
591 c.token = s.next_token++;
592 s.callbacks.push_back(c);
593 if (report && enumeration != GameInputBlockingEnumeration) {
594 s.pending.push_back({c.token, now_us()});
595 later = true;
596 }
597 }
598 if (token) *token = c.token;
599 // Blocking enumeration: the pad is reported before this returns, on the caller's thread.
600 if (report && enumeration == GameInputBlockingEnumeration) call_device(c, now_us());
601 if (later) schedule_delivery();
602 return S_OK;
603 }
604 // The script has no guide button and the pad no keyboard layout: these are accepted and never run.
605 HRESULT STDMETHODCALLTYPE RegisterGuideButtonCallback(IGameInputDevice*, void* context, GameInputGuideButtonCallback fn,
606 GameInputCallbackToken* token) override {
607 return add(CbType::Guide, context, reinterpret_cast<void*>(fn), token);
608 }
609 HRESULT STDMETHODCALLTYPE RegisterKeyboardLayoutCallback(IGameInputDevice*, void* context,
610 GameInputKeyboardLayoutCallback fn,
611 GameInputCallbackToken* token) override {
612 return add(CbType::KeyboardLayout, context, reinterpret_cast<void*>(fn), token);
613 }
614 void STDMETHODCALLTYPE StopCallback(GameInputCallbackToken token) override {
615 std::lock_guard lock(g().mu);
616 for (Callback& c : g().callbacks)
617 if (c.token == token) c.active = false;
618 }
619 // Removes the callback and, unless called from inside a callback, waits for one that is running to return.
620 bool STDMETHODCALLTYPE UnregisterCallback(GameInputCallbackToken token, uint64_t) override {
621 State& s = g();
622 bool found = false;
623 {
624 std::lock_guard lock(s.mu);
625 auto it = std::find_if(s.callbacks.begin(), s.callbacks.end(),
626 [token](const Callback& c) { return c.token == token; });
627 if (it != s.callbacks.end()) {
628 s.callbacks.erase(it);
629 found = true;
630 }
631 }
632 if (found && s.delivering_thread != GetCurrentThreadId()) std::lock_guard wait(s.deliver_mu);
633 return found;
634 }
635 HRESULT STDMETHODCALLTYPE CreateDispatcher(IGameInputDispatcher** out) override {
636 if (!out) return E_POINTER;
637 *out = new Dispatcher;
638 return S_OK;
639 }
640 HRESULT STDMETHODCALLTYPE CreateAggregateDevice(uint32_t, IGameInputDevice** out) override {
641 if (out) *out = nullptr;
642 not_served<15>("CreateAggregateDevice");
643 return E_NOTIMPL;
644 }
645 HRESULT STDMETHODCALLTYPE FindDeviceFromId(const AppLocalDeviceId* id, IGameInputDevice** out) override {
646 if (!out) return E_POINTER;
647 *out = nullptr;
648 if (!id) return E_INVALIDARG;
649 if (std::memcmp(id, &pad().GetDeviceInfo()->deviceId, sizeof *id) != 0) return GAMEINPUT_E_DEVICE_NOT_FOUND;
650 pad().AddRef();
651 *out = &pad();
652 return S_OK;
653 }
654 HRESULT STDMETHODCALLTYPE FindDeviceFromObject(IUnknown*, IGameInputDevice** out) override { return not_found(out); }
655 HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformHandle(HANDLE, IGameInputDevice** out) override { return not_found(out); }
656 HRESULT STDMETHODCALLTYPE FindDeviceFromPlatformString(LPCWSTR, IGameInputDevice** out) override { return not_found(out); }
657 HRESULT STDMETHODCALLTYPE EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) override { return S_OK; }
658 void STDMETHODCALLTYPE SetFocusPolicy(uint32_t) override {}
659
660private:
661 static HRESULT not_found(IGameInputDevice** out) {
662 if (out) *out = nullptr;
663 return GAMEINPUT_E_DEVICE_NOT_FOUND;
664 }
665 static HRESULT add(CbType type, void* context, void* fn, GameInputCallbackToken* token) {
666 if (token) *token = kInvalidCallbackToken;
667 if (!fn) return E_INVALIDARG;
668 std::lock_guard lock(g().mu);
669 const GameInputCallbackToken t = g().next_token++;
670 g().callbacks.push_back({t, type, context, fn, true});
671 if (token) *token = t;
672 return S_OK;
673 }
674 std::atomic<ULONG> refs_{1};
675};
676
677// The scripted object when LEONIDA_INPUT_SCRIPT is set, read once on the first call; null otherwise.
678ScriptedInput* scripted() {
679 static ScriptedInput* const input = []() -> ScriptedInput* {
680 const std::string text = script::env_lower("LEONIDA_INPUT_SCRIPT");
681 if (text.empty()) return nullptr;
682 State& s = g();
683 std::lock_guard lock(s.mu);
684 s.script = script::parse(text);
685 s.log_presses = script::env_lower("LEONIDA_INPUT_LOG") != "0";
686 s.wait_event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
687 s.origin_us = now_us();
688 update(s.origin_us); // the first reading: nothing held unless the script presses at 0 s
689 std::fprintf(stderr,
690 "[rt] gameinput: served without SDL3: one scripted pad for LEONIDA_INPUT_SCRIPT (%zu scripted "
691 "press(es), %zu rejected); controllers and the keyboard pad need SDL3\n",
692 s.script.presses.size(), s.script.rejected);
693 return new ScriptedInput;
694 }();
695 return input;
696}
697
69HRESULT WINAPI GameInputCreate(void** out) { 698HRESULT WINAPI GameInputCreate(void** out) {
70 if (!out) return E_POINTER; 699 if (!out) return E_POINTER;
700 if (ScriptedInput* input = scripted()) {
701 input->AddRef();
702 *out = static_cast<IGameInput*>(input);
703 return S_OK;
704 }
71 g_refs.fetch_add(1); 705 g_refs.fetch_add(1);
72 *out = &g_gameinput; 706 *out = &g_gameinput;
73 static std::atomic<bool> warned{false}; 707 static std::atomic<bool> warned{false};
@@ -78,6 +712,10 @@ HRESULT WINAPI GameInputCreate(void** out) {
78 712
79} // namespace 713} // namespace
80 714
715namespace rt::gameinput_no_sdl {
716void set_clock(ClockFn now) { g_clock.store(now ? now : &qpc_now_us); }
717} // namespace rt::gameinput_no_sdl
718
81SHIM_TABLE(gameinput_no_sdl, 719SHIM_TABLE(gameinput_no_sdl,
82 {"gameinput.dll", "GameInputCreate", reinterpret_cast<void*>(&GameInputCreate)}, 720 {"gameinput.dll", "GameInputCreate", reinterpret_cast<void*>(&GameInputCreate)},
83 // The retail executable imports this one by ordinal, so the registry key is "#1"; without the alias the loader 721 // The retail executable imports this one by ordinal, so the registry key is "#1"; without the alias the loader
diff --git a/runtime/shims/gameinput_no_sdl.h b/runtime/shims/gameinput_no_sdl.h
new file mode 100644
index 000000000..02eef85c6
--- /dev/null
+++ b/runtime/shims/gameinput_no_sdl.h
@@ -0,0 +1,12 @@
1// gameinput.dll without SDL3 (gameinput_no_sdl.cpp): the test seam of its scripted pad.
2#pragma once
3#include <cstdint>
4
5namespace rt::gameinput_no_sdl {
6
7// The clock the scripted pad reads, in microseconds (GetCurrentTimestamp's scale). Set it before the first
8// GameInputCreate, which starts the script's clock; nullptr restores the performance counter.
9using ClockFn = uint64_t (*)();
10void set_clock(ClockFn now_us);
11
12} // namespace rt::gameinput_no_sdl
diff --git a/runtime/shims/gameinput_script.h b/runtime/shims/gameinput_script.h
new file mode 100644
index 000000000..759506750
--- /dev/null
+++ b/runtime/shims/gameinput_script.h
@@ -0,0 +1,180 @@
1// LEONIDA_INPUT_SCRIPT, shared by both GameInput shims: the SDL3 one (gameinput.cpp, where the script drives the
2// keyboard pad) and the one built without SDL3 (gameinput_no_sdl.cpp, where it drives a scripted pad of its own).
3// The parser, the press timeline, the button names and the press log lines live here, once; nothing in this file
4// needs SDL. docs/gameinput.md, "Scripted input", has the format.
5//
6// LEONIDA_INPUT_SCRIPT="a@70,a@85,start@120"
7//
8// Each entry is button@seconds, the seconds counted from the shim's first update. A press is held for kHoldSeconds,
9// then released. Buttons: a b x y start back lb rb up down left right; rsup and rsdown throw the right stick fully up
10// or down for the same time (they replay the stick throws the press log writes). Spaces around an entry are allowed;
11// empty entries, unknown buttons and invalid times (negative, non-finite, trailing text) are counted as rejected.
12#pragma once
13#include <algorithm>
14#include <cctype>
15#include <cmath>
16#include <cstdint>
17#include <cstdio>
18#include <cstdlib>
19#include <string>
20#include <vector>
21
22#include "gameinput_abi.h"
23
24namespace rt::gameinput::script {
25
26constexpr double kHoldSeconds = 0.3;
27
28// One scriptable button: its name in the script and the press log, its GameInput gamepad bit, and its SDL3
29// SDL_GamepadButton number, which the "scripted press of button <n>" line has always carried (tools/stage_timeline.py
30// reads it). gameinput.cpp checks the numbers against SDL's enum.
31struct Button {
32 const char* name;
33 uint32_t bit;
34 int sdl;
35};
36inline constexpr Button kButtons[] = {
37 {"a", gi::GameInputGamepadA, 0}, {"b", gi::GameInputGamepadB, 1},
38 {"x", gi::GameInputGamepadX, 2}, {"y", gi::GameInputGamepadY, 3},
39 {"start", gi::GameInputGamepadMenu, 6}, {"back", gi::GameInputGamepadView, 4},
40 {"lb", gi::GameInputGamepadLeftShoulder, 9}, {"rb", gi::GameInputGamepadRightShoulder, 10},
41 {"up", gi::GameInputGamepadDPadUp, 11}, {"down", gi::GameInputGamepadDPadDown, 12},
42 {"left", gi::GameInputGamepadDPadLeft, 13}, {"right", gi::GameInputGamepadDPadRight, 14},
43};
44
45struct Press {
46 uint32_t button = 0; // a GameInput gamepad bit, or 0 for a stick throw
47 int stick = 0; // +1 rsup, -1 rsdown (GameInput's +Y is up)
48 double at = 0; // seconds
49};
50
51struct Script {
52 std::vector<Press> presses;
53 size_t rejected = 0;
54 uint32_t named = 0; // every button the script presses at least once
55 bool empty() const { return presses.empty(); }
56};
57
58// The script in `text`, matched without regard to case.
59inline Script parse(std::string text) {
60 for (auto& c : text) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
61 Script out;
62 if (text.empty()) return out;
63 constexpr char whitespace[] = " \t\r\n\f\v";
64 size_t items = 0;
65 for (size_t at = 0, end; at <= text.size(); at = end + 1) {
66 ++items;
67 end = std::min(text.find(',', at), text.size());
68 const std::string item = text.substr(at, end - at);
69 const size_t first = item.find_first_not_of(whitespace);
70 const size_t sep = item.find('@');
71 if (sep == std::string::npos || first >= sep) continue;
72 const char* time = item.c_str() + sep + 1;
73 char* tail;
74 const double seconds = std::strtod(time, &tail);
75 if (tail == time || !std::isfinite(seconds) || seconds < 0 ||
76 item.find_first_not_of(whitespace, static_cast<size_t>(tail - item.c_str())) != std::string::npos)
77 continue;
78 const auto is = [&](const char* name) { return item.compare(first, sep - first, name) == 0; };
79 if (is("rsup") || is("rsdown")) {
80 out.presses.push_back({0, is("rsup") ? 1 : -1, seconds});
81 continue;
82 }
83 for (const Button& b : kButtons) {
84 if (is(b.name)) {
85 out.presses.push_back({b.bit, 0, seconds});
86 out.named |= b.bit;
87 break;
88 }
89 }
90 }
91 out.rejected = items - out.presses.size();
92 return out;
93}
94
95// What the script holds `seconds` after its clock started: the buttons (GameInput bits) and the right stick throw.
96// One decision per button: a later entry for the same button must not release what an earlier entry holds (it did:
97// with several entries only the last one ever reached the title).
98struct Held {
99 uint32_t buttons = 0;
100 int stick = 0; // +1 up, -1 down, 0 at rest
101};
102inline Held held_at(const Script& script, double seconds) {
103 Held h;
104 for (const Press& p : script.presses) {
105 if (seconds < p.at || seconds >= p.at + kHoldSeconds) continue;
106 if (p.stick) h.stick = p.stick;
107 else h.buttons |= p.button;
108 }
109 return h;
110}
111
112inline const Button* button_of(uint32_t bit) {
113 for (const Button& b : kButtons)
114 if (b.bit == bit) return &b;
115 return nullptr;
116}
117
118// "[rt] gameinput: scripted press of button <n> at <t> s" for every button the script starts holding: `was` is the
119// previous call's held set and is updated.
120inline void log_scripted(uint32_t held, uint32_t* was, double seconds) {
121 for (const Button& b : kButtons)
122 if ((held & b.bit) && !(*was & b.bit))
123 std::fprintf(stderr, "[rt] gameinput: scripted press of button %d at %.1f s\n", b.sdl, seconds);
124 *was = held;
125}
126
127// The press log (LEONIDA_INPUT_LOG, on unless 0): every newly pressed button and every new right-stick throw in the
128// script's own form, name@seconds, so a session played by hand can be replayed by joining the items with commas.
129inline int stick_throw(float y) { return y > 0.6f ? 1 : y < -0.6f ? -1 : 0; }
130inline void log_presses(uint32_t pressed, float right_y_was, float right_y, double seconds, const char* device) {
131 for (const Button& b : kButtons)
132 if (pressed & b.bit) std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", b.name, seconds, device);
133 const int was = stick_throw(right_y_was), is = stick_throw(right_y);
134 if (is != was && is != 0)
135 std::fprintf(stderr, "[rt] gameinput: press %s@%.1f (%s)\n", is > 0 ? "rsup" : "rsdown", seconds, device);
136}
137
138// UI navigation derived from a gamepad state, the same for every pad (VERIFY against the console's own mapping).
139inline uint32_t ui_navigation(const gi::GameInputGamepadState& g) {
140 using namespace gi;
141 const uint32_t b = g.buttons;
142 const float t = 0.5f;
143 uint32_t u = 0;
144 if (b & GameInputGamepadMenu) u |= GameInputUiNavigationMenu;
145 if (b & GameInputGamepadView) u |= GameInputUiNavigationView;
146 if (b & GameInputGamepadA) u |= GameInputUiNavigationAccept;
147 if (b & GameInputGamepadB) u |= GameInputUiNavigationCancel;
148 if (b & GameInputGamepadX) u |= GameInputUiNavigationContext1;
149 if (b & GameInputGamepadY) u |= GameInputUiNavigationContext2;
150 if (b & GameInputGamepadLeftThumbstick) u |= GameInputUiNavigationContext3;
151 if (b & GameInputGamepadRightThumbstick) u |= GameInputUiNavigationContext4;
152 if ((b & GameInputGamepadDPadUp) || g.leftThumbstickY > t) u |= GameInputUiNavigationUp;
153 if ((b & GameInputGamepadDPadDown) || g.leftThumbstickY < -t) u |= GameInputUiNavigationDown;
154 if ((b & GameInputGamepadDPadLeft) || g.leftThumbstickX < -t) u |= GameInputUiNavigationLeft;
155 if ((b & GameInputGamepadDPadRight) || g.leftThumbstickX > t) u |= GameInputUiNavigationRight;
156 if (b & GameInputGamepadLeftShoulder) u |= GameInputUiNavigationPageLeft;
157 if (b & GameInputGamepadRightShoulder) u |= GameInputUiNavigationPageRight;
158 if (g.leftTrigger > t) u |= GameInputUiNavigationPageUp;
159 if (g.rightTrigger > t) u |= GameInputUiNavigationPageDown;
160 if (g.rightThumbstickY > t) u |= GameInputUiNavigationScrollUp;
161 if (g.rightThumbstickY < -t) u |= GameInputUiNavigationScrollDown;
162 if (g.rightThumbstickX < -t) u |= GameInputUiNavigationScrollLeft;
163 if (g.rightThumbstickX > t) u |= GameInputUiNavigationScrollRight;
164 return u;
165}
166
167// An environment variable in lower case, of any length (a script is easily longer than a fixed buffer, and a value
168// that did not fit used to read as unset). Empty when unset.
169inline std::string env_lower(const char* name) {
170 const DWORD need = GetEnvironmentVariableA(name, nullptr, 0); // with the terminator
171 if (need == 0) return {};
172 std::string s(need, '\0');
173 const DWORD n = GetEnvironmentVariableA(name, s.data(), need);
174 if (n == 0 || n >= need) return {};
175 s.resize(n);
176 for (auto& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
177 return s;
178}
179
180} // namespace rt::gameinput::script
diff --git a/runtime/test/gameinput_no_sdl_test.cpp b/runtime/test/gameinput_no_sdl_test.cpp
index c8443f3b3..a131dc7c9 100644
--- a/runtime/test/gameinput_no_sdl_test.cpp
+++ b/runtime/test/gameinput_no_sdl_test.cpp
@@ -1,28 +1,34 @@
1// gameinput.dll!#1 without SDL3: the retail executable imports GameInputCreate by ordinal, and a build without SDL3 1// gameinput.dll without SDL3 (shims/gameinput_no_sdl.cpp). No controller, no game data.
2// still has to hand back an interface instead of letting the loader fall through to the host's gameinput.dll, which 2//
3// answers with a null pointer that the title dereferences. 3// gameinput_no_sdl_test LEONIDA_INPUT_SCRIPT unset: the identity-only object. The retail executable
4// imports GameInputCreate by ordinal, and a build without SDL3 still has to
5// hand back an interface instead of letting the loader fall through to the
6// host's gameinput.dll, which answers with a null pointer the title
7// dereferences.
8// gameinput_no_sdl_test --input-script LEONIDA_INPUT_SCRIPT set: the scripted pad, found through device callbacks
9// and read at chosen times of a fake clock.
4#include <windows.h> 10#include <windows.h>
5 11
6#include <cstdint> 12#include <cstdint>
7#include <cstdio> 13#include <cstdio>
14#include <cstring>
8 15
16#include "gameinput_abi.h"
17#include "gameinput_no_sdl.h"
9#include "shims.h" 18#include "shims.h"
10 19
20using namespace gi;
21
11namespace { 22namespace {
12int g_failed = 0; 23int g_failed = 0;
13void check(bool ok, const char* what) { 24void check(bool ok, const char* what) {
14 std::printf("%s %s\n", ok ? "ok " : "FAIL ", what); 25 std::printf("%s %s\n", ok ? "ok " : "FAIL ", what);
15 if (!ok) ++g_failed; 26 if (!ok) ++g_failed;
16} 27}
17} // namespace
18 28
19int main() { 29using CreateFn = HRESULT(WINAPI*)(void**);
20 auto create = reinterpret_cast<HRESULT(WINAPI*)(void**)>(rt::shims::find("gameinput.dll", "#1"));
21 auto named = reinterpret_cast<HRESULT(WINAPI*)(void**)>(rt::shims::find("gameinput.dll", "GameInputCreate"));
22 check(create != nullptr, "the ordinal import gameinput.dll!#1 is served");
23 check(named != nullptr, "the name GameInputCreate is served");
24 if (!create) return 1;
25 30
31int identity_only(CreateFn create) {
26 void* object = nullptr; 32 void* object = nullptr;
27 check(create(&object) == S_OK, "GameInputCreate returns S_OK"); 33 check(create(&object) == S_OK, "GameInputCreate returns S_OK");
28 check(object != nullptr, "GameInputCreate hands back a non-null interface"); 34 check(object != nullptr, "GameInputCreate hands back a non-null interface");
@@ -41,6 +47,220 @@ int main() {
41 check(devices == reinterpret_cast<void*>(0x1), "an unserved slot writes nothing to its out-parameter"); 47 check(devices == reinterpret_cast<void*>(0x1), "an unserved slot writes nothing to its out-parameter");
42 48
43 check(create(nullptr) == E_POINTER, "a null out parameter is E_POINTER"); 49 check(create(nullptr) == E_POINTER, "a null out parameter is E_POINTER");
50 return 0;
51}
52
53// ---- the scripted pad ----
54
55uint64_t g_now_us = 7'000'000; // the fake clock; the script's clock starts at GameInputCreate
56uint64_t fake_clock() { return g_now_us; }
57void at(double seconds) { g_now_us = 7'000'000 + static_cast<uint64_t>(seconds * 1e6 + 0.5); }
58
59struct Seen {
60 int calls = 0;
61 IGameInputDevice* device = nullptr;
62 uint32_t current = 0, previous = 0xFFFFFFFF;
63 DWORD thread = 0;
64 HANDLE done = nullptr;
65};
66void CALLBACK on_device(GameInputCallbackToken, void* context, IGameInputDevice* device, uint64_t, uint32_t current,
67 uint32_t previous) {
68 auto* seen = static_cast<Seen*>(context);
69 ++seen->calls;
70 seen->device = device;
71 seen->current = current;
72 seen->previous = previous;
73 seen->thread = GetCurrentThreadId();
74 if (seen->done) SetEvent(seen->done);
75}
76
77struct Pad {
78 uint32_t buttons = 0xFFFFFFFF;
79 float right_y = -2;
80 uint32_t ui = 0xFFFFFFFF;
81 uint64_t seq = 0;
82 bool a_button = false;
83};
84Pad read_at(IGameInput* input, IGameInputDevice* device, double seconds) {
85 at(seconds);
86 Pad p;
87 IGameInputReading* r = nullptr;
88 if (input->GetCurrentReading(GameInputKindGamepad, device, &r) != S_OK || !r) return p;
89 GameInputGamepadState s{};
90 if (r->GetGamepadState(&s)) p.buttons = s.buttons, p.right_y = s.rightThumbstickY;
91 GameInputUiNavigationState u{};
92 if (r->GetUiNavigationState(&u)) p.ui = u.buttons;
93 p.seq = r->GetSequenceNumber(GameInputKindGamepad);
94 bool buttons[15] = {};
95 if (r->GetControllerButtonState(15, buttons) == 15) p.a_button = buttons[0];
96 r->Release();
97 return p;
98}
99
100int scripted_pad(CreateFn create) {
101 // Four presses (two overlapping A presses, Menu, a right-stick throw) and three rejected entries.
102 SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", "a@1, START@2.5 ,a@1.2,rsup@4,bogus@1,a@-1,");
103 rt::gameinput_no_sdl::set_clock(fake_clock);
104 at(0);
105
106 IGameInput* input = nullptr;
107 check(create(reinterpret_cast<void**>(&input)) == S_OK && input, "script: GameInputCreate returns an instance");
108 if (!input) return 1;
109 IUnknown* unk = nullptr;
110 check(input->QueryInterface(IID_IGameInput, reinterpret_cast<void**>(&unk)) == S_OK && unk == input,
111 "script: QueryInterface(IID_IGameInput) is the same object");
112 if (unk) unk->Release();
113 check(input->GetCurrentTimestamp() == g_now_us, "script: GetCurrentTimestamp reads the shim's clock");
114
115 // Device callbacks: a blocking enumeration reports the pad before it returns, on this thread.
116 Seen blocking;
117 GameInputCallbackToken token = 0;
118 check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceConnected,
119 GameInputBlockingEnumeration, &blocking, on_device, &token) == S_OK &&
120 token != kInvalidCallbackToken,
121 "script: RegisterDeviceCallback (blocking) is served");
122 check(blocking.calls == 1 && blocking.device && blocking.thread == GetCurrentThreadId(),
123 "script: blocking enumeration reports one device on the caller's thread");
124 check((blocking.current & GameInputDeviceConnected) && blocking.previous == GameInputDeviceNoStatus,
125 "script: the device is reported connected, from no status");
126 IGameInputDevice* device = blocking.device;
127 if (!device) return 1;
128 const GameInputDeviceInfo* info = device->GetDeviceInfo();
129 check(info && info->deviceFamily == GameInputFamilyXboxOne && (info->supportedInput & GameInputKindGamepad),
130 "script: the device is an Xbox One gamepad");
131 check(info && info->gamepadInfo && info->gamepadInfo->aButtonLabel == GameInputLabelXboxA,
132 "script: the A button carries the Xbox A label");
133 check(info && info->displayName && info->displayName->sizeInBytes > 0, "script: the device has a display name");
134 check(device->GetDeviceStatus() & GameInputDeviceConnected, "script: GetDeviceStatus says connected");
135 IGameInputDevice* found = nullptr;
136 check(info && input->FindDeviceFromId(&info->deviceId, &found) == S_OK && found == device,
137 "script: FindDeviceFromId finds the pad");
138 if (found) found->Release();
139 check(input->UnregisterCallback(token, 0), "script: the blocking callback unregisters");
140
141 // No enumeration, or a status filter the pad does not match: nothing is reported.
142 Seen quiet;
143 check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceConnected, GameInputNoEnumeration,
144 &quiet, on_device, &token) == S_OK,
145 "script: RegisterDeviceCallback without enumeration is served");
146 input->UnregisterCallback(token, 0);
147 check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceWireless,
148 GameInputBlockingEnumeration, &quiet, on_device, &token) == S_OK,
149 "script: RegisterDeviceCallback with another status filter is served");
150 input->UnregisterCallback(token, 0);
151 check(input->RegisterDeviceCallback(nullptr, GameInputKindKeyboard, GameInputDeviceAnyStatus,
152 GameInputBlockingEnumeration, &quiet, on_device, &token) == S_OK,
153 "script: RegisterDeviceCallback for keyboards is served");
154 input->UnregisterCallback(token, 0);
155 check(quiet.calls == 0, "script: no report without enumeration, for another status or another kind");
156
157 // Async enumeration: reported after the call, from another thread.
158 Seen async;
159 async.done = CreateEventW(nullptr, TRUE, FALSE, nullptr);
160 check(input->RegisterDeviceCallback(nullptr, GameInputKindUnknown, GameInputDeviceAnyStatus,
161 GameInputAsyncEnumeration, &async, on_device, &token) == S_OK,
162 "script: RegisterDeviceCallback (async) is served");
163 check(WaitForSingleObject(async.done, 5000) == WAIT_OBJECT_0 && async.calls == 1 && async.device == device,
164 "script: async enumeration reports the pad");
165 check(async.thread != GetCurrentThreadId(), "script: async enumeration reports it from another thread");
166 input->UnregisterCallback(token, 0);
167
168 // With a dispatcher, the title's Dispatch delivers the report on its own thread.
169 IGameInputDispatcher* dispatcher = nullptr;
170 check(input->CreateDispatcher(&dispatcher) == S_OK && dispatcher, "script: CreateDispatcher is served");
171 if (dispatcher) {
172 HANDLE wait = nullptr;
173 check(dispatcher->OpenWaitHandle(&wait) == S_OK && wait, "script: the dispatcher has a wait handle");
174 Seen dispatched;
175 check(input->RegisterDeviceCallback(nullptr, GameInputKindGamepad, GameInputDeviceConnected,
176 GameInputAsyncEnumeration, &dispatched, on_device, &token) == S_OK,
177 "script: RegisterDeviceCallback (async, with a dispatcher) is served");
178 check(wait && WaitForSingleObject(wait, 5000) == WAIT_OBJECT_0, "script: the wait handle is signalled");
179 check(dispatched.calls == 0, "script: nothing is delivered before Dispatch");
180 check(!dispatcher->Dispatch(0) && dispatched.calls == 1 && dispatched.thread == GetCurrentThreadId(),
181 "script: Dispatch delivers the report on the caller's thread");
182 input->UnregisterCallback(token, 0);
183 if (wait) CloseHandle(wait);
184 dispatcher->Release();
185 }
186
187 // Readings follow the script's timeline: each press is held for 0.3 s, then released.
188 const Pad start = read_at(input, nullptr, 0.0);
189 check(start.buttons == 0 && start.right_y == 0, "script: nothing is held at 0 s");
190 const Pad idle = read_at(input, device, 0.9);
191 check(idle.buttons == 0 && idle.seq == start.seq, "script: no new reading while nothing changes");
192 const Pad a = read_at(input, device, 1.0);
193 check(a.buttons == GameInputGamepadA && a.a_button && a.seq > idle.seq, "script: A is held at 1.0 s");
194 check(a.ui == GameInputUiNavigationAccept, "script: A reads as UI Accept");
195 check(read_at(input, device, 1.25).buttons == GameInputGamepadA, "script: overlapping A presses hold A at 1.25 s");
196 check(read_at(input, device, 1.45).buttons == GameInputGamepadA,
197 "script: a later press of the same button is not cut by the earlier one's release");
198 const Pad released = read_at(input, device, 1.55);
199 check(released.buttons == 0 && !released.a_button, "script: A is released after its last 0.3 s hold");
200 const Pad menu = read_at(input, device, 2.6);
201 check(menu.buttons == GameInputGamepadMenu && menu.ui == GameInputUiNavigationMenu,
202 "script: START (any case) holds Menu at 2.6 s");
203 check(read_at(input, device, 2.85).buttons == 0, "script: Menu is released at 2.85 s");
204 const Pad up = read_at(input, device, 4.1);
205 check(up.buttons == 0 && up.right_y == 1.0f && up.ui == GameInputUiNavigationScrollUp,
206 "script: rsup throws the right stick up at 4.1 s");
207 check(read_at(input, device, 4.5).right_y == 0, "script: the stick is back at rest at 4.5 s");
208 check(read_at(input, device, 60).buttons == 0, "script: nothing is held after the script ends");
209
210 // The history: the reading before the current one is the stick throw, and the one after that throw is the rest.
211 IGameInputReading* now = nullptr;
212 IGameInputReading* before = nullptr;
213 IGameInputReading* after = nullptr;
214 check(input->GetCurrentReading(GameInputKindUnknown, nullptr, &now) == S_OK && now, "script: a current reading");
215 if (now) {
216 GameInputGamepadState s{};
217 check(input->GetPreviousReading(now, GameInputKindGamepad, device, &before) == S_OK && before &&
218 before->GetGamepadState(&s) && s.rightThumbstickY == 1.0f,
219 "script: GetPreviousReading steps back to the stick throw");
220 if (before) {
221 check(input->GetNextReading(before, GameInputKindGamepad, nullptr, &after) == S_OK && after == now,
222 "script: GetNextReading steps forward to the current reading");
223 before->Release();
224 }
225 if (after) after->Release();
226 IGameInputReading* none = nullptr;
227 check(input->GetNextReading(now, GameInputKindUnknown, nullptr, &none) == GAMEINPUT_E_READING_NOT_FOUND &&
228 !none,
229 "script: nothing after the current reading");
230 IGameInputDevice* of = nullptr;
231 now->GetDevice(&of);
232 check(of == device, "script: a reading belongs to the pad");
233 if (of) of->Release();
234 now->Release();
235 }
236
237 IGameInputReading* motion = nullptr;
238 check(input->GetCurrentReading(GameInputKindMotion, nullptr, &motion) == GAMEINPUT_E_READING_NOT_FOUND && !motion,
239 "script: the pad has no motion readings");
240 GameInputCallbackToken reading_token = 1;
241 check(input->RegisterReadingCallback(nullptr, GameInputKindGamepad, 0, nullptr, nullptr, &reading_token) ==
242 E_NOTIMPL &&
243 reading_token == kInvalidCallbackToken,
244 "script: reading callbacks still need SDL3");
245 void* second = nullptr;
246 check(create(&second) == S_OK && second == input, "script: a second GameInputCreate returns the same instance");
247 if (second) static_cast<IGameInput*>(second)->Release();
248 input->Release();
249 return 0;
250}
251} // namespace
252
253int main(int argc, char** argv) {
254 auto create = reinterpret_cast<CreateFn>(rt::shims::find("gameinput.dll", "#1"));
255 auto named = reinterpret_cast<CreateFn>(rt::shims::find("gameinput.dll", "GameInputCreate"));
256 check(create != nullptr, "the ordinal import gameinput.dll!#1 is served");
257 check(named != nullptr, "the name GameInputCreate is served");
258 if (!create) return 1;
259
260 const bool with_script = argc == 2 && std::strcmp(argv[1], "--input-script") == 0;
261 SetEnvironmentVariableA("LEONIDA_INPUT_SCRIPT", nullptr);
262 SetEnvironmentVariableA("LEONIDA_INPUT_LOG", nullptr);
263 const int early = with_script ? scripted_pad(create) : identity_only(create);
44 std::printf("%d failure(s)\n", g_failed); 264 std::printf("%d failure(s)\n", g_failed);
45 return g_failed ? 1 : 0; 265 return early || g_failed ? 1 : 0;
46} 266}