upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims/gameinput.cpp
diff options
context:
space:
mode:
authortedin7 <tommasoderosa94@gmail.com>2026-11-23 23:14:07 +0100
committerClaude <noreply@anthropic.com>2026-11-25 13:25:48 +0000
commit9a96b8ba6aaf2fc8ed3f3ad5177d0e3f420dc62c (patch)
treeb2576154c60e467ceb70b3ec2607e827091e63bc /runtime/shims/gameinput.cpp
parent384abe5b06d08e349f4b4e4394c68f036da47dc7 (diff)
gameinput: preserve controller transitions between polls
Diffstat (limited to 'runtime/shims/gameinput.cpp')
-rw-r--r--runtime/shims/gameinput.cpp188
1 files changed, 118 insertions, 70 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 47e9aa941..d9cef893c 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -973,8 +973,6 @@ bool deliver_within(uint64_t quota_us) {
973 973
974uint16_t to_u16(float v) { return static_cast<uint16_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); } 974uint16_t to_u16(float v) { return static_cast<uint16_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); }
975 975
976float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); }
977
978float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); } 976float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); }
979 977
980bool is_keyboard_pad(SDL_JoystickID jid); // with the keyboard pad below 978bool is_keyboard_pad(SDL_JoystickID jid); // with the keyboard pad below
@@ -1050,10 +1048,23 @@ void apply_prompt_config() {
1050 leonida::input_family_name(g_tracker.active())); 1048 leonida::input_family_name(g_tracker.active()));
1051} 1049}
1052 1050
1053Snapshot read_pad(Device* d) { 1051void set_pad_axis(Snapshot& s, SDL_GamepadAxis axis, Sint16 value) {
1054 SDL_Gamepad* p = d->pad; 1052 static constexpr float GameInputGamepadState::* kFields[] = {
1055 Snapshot s; 1053 &GameInputGamepadState::leftThumbstickX, &GameInputGamepadState::leftThumbstickY,
1056 auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); }; 1054 &GameInputGamepadState::rightThumbstickX, &GameInputGamepadState::rightThumbstickY,
1055 &GameInputGamepadState::leftTrigger, &GameInputGamepadState::rightTrigger,
1056 };
1057 static_assert(SDL_GAMEPAD_AXIS_COUNT == kAxisCount && SDL_GAMEPAD_AXIS_RIGHT_TRIGGER == kAxisCount - 1);
1058 // GameInput sticks use +Y up; the controller-axis view puts stick rest at 0.5. Triggers use 0..1 in both views.
1059 float v = std::max(-1.0f, value / 32767.0f);
1060 if (axis == SDL_GAMEPAD_AXIS_LEFTY || axis == SDL_GAMEPAD_AXIS_RIGHTY) v = -v;
1061 const bool trigger = axis >= SDL_GAMEPAD_AXIS_LEFT_TRIGGER;
1062 if (trigger) v = std::max(0.0f, v);
1063 s.gamepad.*kFields[axis] = v;
1064 s.axes[axis] = trigger ? v : (v + 1) * 0.5f;
1065}
1066
1067void map_pad_buttons_and_navigation(Snapshot& s) {
1057 struct Map { SDL_GamepadButton sdl; uint32_t gi; }; 1068 struct Map { SDL_GamepadButton sdl; uint32_t gi; };
1058 static const Map kMap[] = { 1069 static const Map kMap[] = {
1059 {SDL_GAMEPAD_BUTTON_START, GameInputGamepadMenu}, 1070 {SDL_GAMEPAD_BUTTON_START, GameInputGamepadMenu},
@@ -1071,30 +1082,25 @@ Snapshot read_pad(Device* d) {
1071 {SDL_GAMEPAD_BUTTON_LEFT_STICK, GameInputGamepadLeftThumbstick}, 1082 {SDL_GAMEPAD_BUTTON_LEFT_STICK, GameInputGamepadLeftThumbstick},
1072 {SDL_GAMEPAD_BUTTON_RIGHT_STICK, GameInputGamepadRightThumbstick}, 1083 {SDL_GAMEPAD_BUTTON_RIGHT_STICK, GameInputGamepadRightThumbstick},
1073 }; 1084 };
1085 s.gamepad.buttons = 0;
1074 for (const Map& m : kMap) 1086 for (const Map& m : kMap)
1075 if (down(m.sdl)) s.gamepad.buttons |= m.gi; 1087 if (s.buttons[m.sdl]) s.gamepad.buttons |= m.gi;
1076 // GameInput: sticks in -1..1 with +Y up, triggers in 0..1. SDL: +Y down, -32768..32767, triggers 0..32767. 1088 s.guide = s.buttons[SDL_GAMEPAD_BUTTON_GUIDE];
1077 s.gamepad.leftThumbstickX = axis(p, SDL_GAMEPAD_AXIS_LEFTX); 1089
1078 s.gamepad.leftThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_LEFTY); 1090 s.ui = rt::gameinput::script::ui_navigation(s.gamepad);
1079 s.gamepad.rightThumbstickX = axis(p, SDL_GAMEPAD_AXIS_RIGHTX); 1091}
1080 s.gamepad.rightThumbstickY = -axis(p, SDL_GAMEPAD_AXIS_RIGHTY); 1092
1081 s.gamepad.leftTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_LEFT_TRIGGER)); 1093Snapshot read_pad(Device* d) {
1082 s.gamepad.rightTrigger = std::max(0.0f, axis(p, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER)); 1094 SDL_Gamepad* p = d->pad;
1083 1095 Snapshot s;
1084 // Controller axes, 0..1 with 0.5 at rest for the sticks (VERIFY: the raw-axis convention of a GameInput gamepad). 1096 for (uint32_t i = 0; i < kAxisCount; ++i) {
1085 s.axes[0] = (s.gamepad.leftThumbstickX + 1) * 0.5f; 1097 const auto axis = static_cast<SDL_GamepadAxis>(i);
1086 s.axes[1] = (s.gamepad.leftThumbstickY + 1) * 0.5f; 1098 set_pad_axis(s, axis, SDL_GetGamepadAxis(p, axis));
1087 s.axes[2] = (s.gamepad.rightThumbstickX + 1) * 0.5f; 1099 }
1088 s.axes[3] = (s.gamepad.rightThumbstickY + 1) * 0.5f; 1100 for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = SDL_GetGamepadButton(p, static_cast<SDL_GamepadButton>(i));
1089 s.axes[4] = s.gamepad.leftTrigger; 1101 map_pad_buttons_and_navigation(s);
1090 s.axes[5] = s.gamepad.rightTrigger; 1102
1091 for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast<SDL_GamepadButton>(i)); 1103 // SDL supplies zeros before the first sensor sample. Use nonzero acceleration to detect the first sample.
1092 s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE);
1093
1094 // Motion, normalised against the maxima motionInfo reports (the ABI's fraction convention). Sensors were enabled
1095 // when the pad was opened; a pad whose sensor read fails just reports no motion this poll. SDL answers reads
1096 // with zeros before the device's first sample arrives, and gravity makes a real accelerometer never read
1097 // exactly zero, so all-zero accel means "no sample yet" and the reading carries no motion at all.
1098 if (d->has_motion) { 1104 if (d->has_motion) {
1099 float accel[3], gyro[3]; 1105 float accel[3], gyro[3];
1100 if (SDL_GetGamepadSensorData(p, SDL_SENSOR_ACCEL, accel, 3) && 1106 if (SDL_GetGamepadSensorData(p, SDL_SENSOR_ACCEL, accel, 3) &&
@@ -1107,16 +1113,13 @@ Snapshot read_pad(Device* d) {
1107 s.motion.angularVelocityX = norm(gyro[0], kMaxAngularVelocity); 1113 s.motion.angularVelocityX = norm(gyro[0], kMaxAngularVelocity);
1108 s.motion.angularVelocityY = norm(gyro[1], kMaxAngularVelocity); 1114 s.motion.angularVelocityY = norm(gyro[1], kMaxAngularVelocity);
1109 s.motion.angularVelocityZ = norm(gyro[2], kMaxAngularVelocity); 1115 s.motion.angularVelocityZ = norm(gyro[2], kMaxAngularVelocity);
1110 // SDL's gamepad API has no compass and the shim synthesises no orientation, so those stay zero and 1116 // SDL supplies neither compass nor orientation data.
1111 // unknown rather than a made-up value.
1112 s.motion.accelerometerAccuracy = GameInputMotionAccuracyHigh; 1117 s.motion.accelerometerAccuracy = GameInputMotionAccuracyHigh;
1113 s.motion.gyroscopeAccuracy = GameInputMotionAccuracyHigh; 1118 s.motion.gyroscopeAccuracy = GameInputMotionAccuracyHigh;
1114 s.motion.magnetometerAccuracy = GameInputMotionAccuracyUnknown; 1119 s.motion.magnetometerAccuracy = GameInputMotionAccuracyUnknown;
1115 s.motion.orientationAccuracy = GameInputMotionAccuracyUnknown; 1120 s.motion.orientationAccuracy = GameInputMotionAccuracyUnknown;
1116 } 1121 }
1117 } 1122 }
1118
1119 s.ui = rt::gameinput::script::ui_navigation(s.gamepad);
1120 return s; 1123 return s;
1121} 1124}
1122 1125
@@ -1932,13 +1935,15 @@ bool init_sdl() {
1932#ifdef SDL_HINT_JOYSTICK_GAMEINPUT 1935#ifdef SDL_HINT_JOYSTICK_GAMEINPUT
1933 SDL_SetHint(SDL_HINT_JOYSTICK_GAMEINPUT, "0"); 1936 SDL_SetHint(SDL_HINT_JOYSTICK_GAMEINPUT, "0");
1934#endif 1937#endif
1935 SDL_SetGamepadEventsEnabled(false); // the shim reads state directly; nothing drains an event queue
1936 if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) { 1938 if (!SDL_InitSubSystem(SDL_INIT_GAMEPAD)) {
1937 std::fprintf(stderr, "[rt] gameinput: SDL gamepad init failed: %s; no controllers\n", SDL_GetError()); 1939 std::fprintf(stderr, "[rt] gameinput: SDL gamepad init failed: %s; no controllers\n", SDL_GetError());
1938 s.sdl_failed = true; 1940 s.sdl_failed = true;
1939 return false; 1941 return false;
1940 } 1942 }
1941 SDL_SetGamepadEventsEnabled(false); 1943 SDL_SetGamepadEventsEnabled(false);
1944 SDL_SetEventEnabled(SDL_EVENT_GAMEPAD_AXIS_MOTION, true);
1945 SDL_SetEventEnabled(SDL_EVENT_GAMEPAD_BUTTON_DOWN, true);
1946 SDL_SetEventEnabled(SDL_EVENT_GAMEPAD_BUTTON_UP, true);
1942 s.sdl_ready = true; 1947 s.sdl_ready = true;
1943 const int v = SDL_GetVersion(); 1948 const int v = SDL_GetVersion();
1944 std::fprintf(stderr, "[rt] gameinput: SDL %d.%d.%d gamepads\n", SDL_VERSIONNUM_MAJOR(v), SDL_VERSIONNUM_MINOR(v), 1949 std::fprintf(stderr, "[rt] gameinput: SDL %d.%d.%d gamepads\n", SDL_VERSIONNUM_MAJOR(v), SDL_VERSIONNUM_MINOR(v),
@@ -1946,6 +1951,72 @@ bool init_sdl() {
1946 return true; 1951 return true;
1947} 1952}
1948 1953
1954std::vector<SDL_Event> take_pad_events() {
1955 // SDL translates joystick events into gamepad events synchronously. Drain the underlying joystick queue
1956 // as well so this headless input loop cannot fill SDL's queue with events it has already handled.
1957 SDL_FlushEvents(SDL_EVENT_JOYSTICK_AXIS_MOTION, SDL_EVENT_JOYSTICK_UPDATE_COMPLETE);
1958 SDL_FlushEvents(SDL_EVENT_GAMEPAD_ADDED, SDL_EVENT_GAMEPAD_STEAM_HANDLE_UPDATED);
1959 constexpr auto first = SDL_EVENT_GAMEPAD_AXIS_MOTION;
1960 constexpr auto last = SDL_EVENT_GAMEPAD_BUTTON_UP;
1961 const int count = SDL_PeepEvents(nullptr, 0, SDL_PEEKEVENT, first, last);
1962 if (count <= 0) return {};
1963 std::vector<SDL_Event> events(count);
1964 const int taken = SDL_PeepEvents(events.data(), count, SDL_GETEVENT, first, last);
1965 events.resize(std::max(taken, 0));
1966 return events;
1967}
1968
1969void publish_pad_sample(Device* d, const Snapshot& snap, uint64_t now, bool motion_tick = false) {
1970 const bool guide_changed = d->last_snap.guide != snap.guide;
1971 const bool changed = !(d->last_snap == snap);
1972 // Every press is logged in LEONIDA_INPUT_SCRIPT's own form (name@seconds), so a session played by hand can
1973 // be replayed unattended: join the logged items with commas. The right stick's vertical throws (what scrolls
1974 // a page) are logged as rsup/rsdown. LEONIDA_INPUT_LOG=0 turns the lines off.
1975 {
1976 static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0";
1977 static const ULONGLONG log_origin = GetTickCount64();
1978 if (log_presses)
1979 rt::gameinput::script::log_presses(snap.gamepad.buttons & ~d->last_snap.gamepad.buttons,
1980 d->last_snap.gamepad.rightThumbstickY, snap.gamepad.rightThumbstickY,
1981 (GetTickCount64() - log_origin) / 1000.0, d->name.c_str());
1982 }
1983 d->last_snap = snap;
1984 // The first observation of a newly opened pad is a baseline, even if a button is held.
1985 if (const leonida::InputEdge edge = g_tracker.observe(d->id, d->family, sample_of(snap), now);
1986 edge != leonida::InputEdge::None) {
1987 publish_active();
1988 if (!g_tracker.forced())
1989 std::fprintf(stderr, "[rt] gameinput: input in use: %s (%s, %s)\n",
1990 leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge));
1991 }
1992 if (!changed && !motion_tick) return;
1993 std::lock_guard lock(g().mu);
1994 queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0});
1995 if (guide_changed) queue_event({CbType::Guide, d, nullptr, now, 0, 0, snap.guide, 0});
1996}
1997
1998void replay_pad_events(Device* d, const std::vector<SDL_Event>& events, uint64_t now) {
1999 std::optional<Snapshot> pending;
2000 Uint64 timestamp = 0;
2001 for (const SDL_Event& e : events) {
2002 const bool axis = e.type == SDL_EVENT_GAMEPAD_AXIS_MOTION;
2003 const SDL_JoystickID id = axis ? e.gaxis.which : e.gbutton.which;
2004 const uint32_t index = axis ? e.gaxis.axis : e.gbutton.button;
2005 if (id != d->id || index >= (axis ? kAxisCount : kButtonCount)) continue;
2006
2007 if (!pending) {
2008 pending = d->last_snap;
2009 } else if (timestamp != e.common.timestamp) {
2010 map_pad_buttons_and_navigation(*pending);
2011 publish_pad_sample(d, *pending, now);
2012 }
2013 timestamp = e.common.timestamp;
2014 if (axis) set_pad_axis(*pending, static_cast<SDL_GamepadAxis>(index), e.gaxis.value);
2015 else pending->buttons[index] = e.gbutton.down;
2016 }
2017 // The final group is represented by the fresh snapshot, which also picks up motion and raw HID state.
2018}
2019
1949void poll_once() { 2020void poll_once() {
1950 State& s = g(); 2021 State& s = g();
1951 std::lock_guard pl(s.poll_mu); 2022 std::lock_guard pl(s.poll_mu);
@@ -1954,6 +2025,7 @@ void poll_once() {
1954 update_keyboard_pad(); 2025 update_keyboard_pad();
1955 SDL_UpdateGamepads(); 2026 SDL_UpdateGamepads();
1956 const uint64_t now = now_us(); 2027 const uint64_t now = now_us();
2028 const auto events = take_pad_events();
1957 2029
1958 int count = 0; 2030 int count = 0;
1959 SDL_JoystickID* ids = SDL_GetGamepads(&count); 2031 SDL_JoystickID* ids = SDL_GetGamepads(&count);
@@ -1968,6 +2040,11 @@ void poll_once() {
1968 for (Device* d : connected) 2040 for (Device* d : connected)
1969 if (std::find(present.begin(), present.end(), d->id) == present.end() || !SDL_GamepadConnected(d->pad)) 2041 if (std::find(present.begin(), present.end(), d->id) == present.end() || !SDL_GamepadConnected(d->pad))
1970 close_pad(d, now); 2042 close_pad(d, now);
2043 size_t previously_open;
2044 {
2045 std::lock_guard lock(s.mu);
2046 previously_open = s.connected.size();
2047 }
1971 for (SDL_JoystickID jid : present) { 2048 for (SDL_JoystickID jid : present) {
1972 bool known = false; 2049 bool known = false;
1973 { 2050 {
@@ -1981,44 +2058,15 @@ void poll_once() {
1981 std::lock_guard lock(s.mu); 2058 std::lock_guard lock(s.mu);
1982 connected = s.connected; 2059 connected = s.connected;
1983 } 2060 }
1984 for (Device* d : connected) { 2061 for (size_t i = 0; i < connected.size(); ++i) {
2062 Device* d = connected[i];
2063 const uint64_t last_reading_us = d->last_reading_us;
2064 if (i < previously_open) replay_pad_events(d, events, now);
1985 Snapshot snap = read_pad(d); 2065 Snapshot snap = read_pad(d);
1986 read_raw(d, &snap); 2066 read_raw(d, &snap);
1987 const bool guide_changed = d->last_snap.guide != snap.guide; 2067 // A pad with sensors still streams readings at ~125 Hz when the controls stay idle.
1988 const bool changed = !(d->last_snap == snap); 2068 const bool motion_tick = snap.has_motion && now - last_reading_us >= kMotionReadingUs;
1989 // Every press is logged in LEONIDA_INPUT_SCRIPT's own form (name@seconds), so a session played by hand can 2069 publish_pad_sample(d, snap, now, motion_tick);
1990 // be replayed unattended: join the logged items with commas. The right stick's vertical throws (what scrolls
1991 // a page) are logged as rsup/rsdown. LEONIDA_INPUT_LOG=0 turns the lines off.
1992 {
1993 static const bool log_presses = env("LEONIDA_INPUT_LOG") != "0";
1994 static const ULONGLONG log_origin = GetTickCount64();
1995 if (log_presses)
1996 rt::gameinput::script::log_presses(snap.gamepad.buttons & ~d->last_snap.gamepad.buttons,
1997 d->last_snap.gamepad.rightThumbstickY, snap.gamepad.rightThumbstickY,
1998 (GetTickCount64() - log_origin) / 1000.0, d->name.c_str());
1999 }
2000 d->last_snap = snap;
2001 // A newly opened pad's first sample here is its baseline (active_input.h), so connecting a pad with a button
2002 // held changes nothing.
2003 if (const leonida::InputEdge edge = g_tracker.observe(d->id, d->family, sample_of(snap), now);
2004 edge != leonida::InputEdge::None) {
2005 publish_active();
2006 if (!g_tracker.forced())
2007 std::fprintf(stderr, "[rt] gameinput: input in use: %s (%s, %s)\n",
2008 leonida::input_family_name(d->family), d->name.c_str(), leonida::input_edge_name(edge));
2009 }
2010 // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads
2011 // between its frames is never stuck at the last button event; pads without sensors only read on change, as
2012 // before. push_reading stamps last_reading_us, so the cadence follows the actual history.
2013 const bool motion_tick = snap.has_motion && now - d->last_reading_us >= kMotionReadingUs;
2014 if (changed || motion_tick) {
2015 std::lock_guard lock(s.mu);
2016 queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0});
2017 }
2018 if (guide_changed) {
2019 std::lock_guard lock(s.mu);
2020 queue_event({CbType::Guide, d, nullptr, now, 0, 0, snap.guide, 0});
2021 }
2022 refresh_battery(d, now); 2070 refresh_battery(d, now);
2023 apply_output(d, now); 2071 apply_output(d, now);
2024 } 2072 }