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:
authormarquezini <felipemarquesini10@gmail.com>2026-11-22 16:32:27 -0300
committermarquezini <felipemarquesini10@gmail.com>2026-11-22 16:32:48 -0300
commitf5907ef65ab326d92db9d4035b2899e4fe57b688 (patch)
tree35804b3d3a38d528098be436a9d84d90631e83c2 /runtime/shims/gameinput.cpp
parente7c83353c7aabdffa873f963f20d9ab6a1b938a9 (diff)
parent162821017ea3c286c8bec860f3ff94f037912061 (diff)
Merge main (873a952a) into the RT-176 branch
Diffstat (limited to 'runtime/shims/gameinput.cpp')
-rw-r--r--runtime/shims/gameinput.cpp129
1 files changed, 121 insertions, 8 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 2acf5e381..71ab21572 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -107,6 +107,8 @@ rt::gameinput::Config read_config() {
107 else if (!t.empty() && t != "rumble") std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str()); 107 else if (!t.empty() && t != "rumble") std::fprintf(stderr, "[rt] gameinput: LEONIDA_DS_TRIGGERS=%s unknown, using rumble\n", t.c_str());
108 if (const std::string g = env("LEONIDA_DS_TRIGGER_GAIN"); !g.empty()) 108 if (const std::string g = env("LEONIDA_DS_TRIGGER_GAIN"); !g.empty())
109 c.ds_trigger_gain = std::clamp(static_cast<float>(std::atof(g.c_str())), 0.0f, 4.0f); 109 c.ds_trigger_gain = std::clamp(static_cast<float>(std::atof(g.c_str())), 0.0f, 4.0f);
110 if (const std::string g = env("LEONIDA_MOUSE_SENSITIVITY"); !g.empty())
111 c.mouse_sensitivity = std::clamp(static_cast<float>(std::atof(g.c_str())), 0.1f, 10.0f);
110 if (const std::string f = env("LEONIDA_DS_TRIGGER_FREQ"); !f.empty()) 112 if (const std::string f = env("LEONIDA_DS_TRIGGER_FREQ"); !f.empty())
111 c.ds_trigger_frequency = static_cast<uint8_t>(std::clamp(std::atoi(f.c_str()), 1, 255)); 113 c.ds_trigger_frequency = static_cast<uint8_t>(std::clamp(std::atoi(f.c_str()), 1, 255));
112 if (const std::string l = env("LEONIDA_DS_LIGHTBAR"); !l.empty()) { 114 if (const std::string l = env("LEONIDA_DS_LIGHTBAR"); !l.empty()) {
@@ -910,8 +912,76 @@ constexpr int kMouseDecayNum = 7, kMouseDecayDen = 8;
910 912
911bool async_key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; } 913bool async_key_down(int vk) { return (GetAsyncKeyState(vk) & 0x8000) != 0; }
912 914
913// shortcut: plain cursor deltas stop at the screen edge; capture or recenter the cursor if that matters in game. 915// ---- raw mouse input (its own thread) ----
916//
917// The cursor stops at the edge of the screen, so cursor deltas stop too. Raw input reports what the mouse itself
918// moved, with no edge and no pointer acceleration. A message-only window (never shown) on its own thread receives
919// WM_INPUT and adds each movement to a running total; system_cursor_pos then returns that total as an edgeless
920// "cursor", and update_keyboard_pad takes the difference between polls exactly as it did with the real cursor.
921std::atomic<long long> g_raw_x{0}, g_raw_y{0}; // total raw movement since the thread started, mouse counts
922std::atomic<bool> g_raw_ready{false}; // registration worked; system_cursor_pos uses the totals
923std::atomic<bool> g_raw_started{false}; // the thread is started once per process
924
925LRESULT CALLBACK raw_mouse_proc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) {
926 if (msg == WM_INPUT) {
927 RAWINPUT raw{};
928 UINT size = sizeof(raw);
929 if (GetRawInputData(reinterpret_cast<HRAWINPUT>(lp), RID_INPUT, &raw, &size, sizeof(RAWINPUTHEADER)) !=
930 static_cast<UINT>(-1) &&
931 raw.header.dwType == RIM_TYPEMOUSE && !(raw.data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE)) {
932 // Relative movement only: absolute reports (remote desktop, some VMs, tablets) are positions, not
933 // movement, and would make the stick jump.
934 g_raw_x += raw.data.mouse.lLastX;
935 g_raw_y += raw.data.mouse.lLastY; // +Y is down, as for the cursor
936 }
937 }
938 return DefWindowProcW(hwnd, msg, wp, lp); // also for WM_INPUT, which lets Windows clean up the input
939}
940
941void raw_mouse_thread() {
942 const HINSTANCE inst = GetModuleHandleW(nullptr);
943 WNDCLASSEXW wc{};
944 wc.cbSize = sizeof(wc);
945 wc.lpfnWndProc = raw_mouse_proc;
946 wc.hInstance = inst;
947 wc.lpszClassName = L"LeonidaRawMouse";
948 RegisterClassExW(&wc);
949 // HWND_MESSAGE: a window that is never shown and only receives messages. It must be created on the thread that
950 // runs the message loop below, because a window's messages go to the thread that created it.
951 HWND hwnd = CreateWindowExW(0, L"LeonidaRawMouse", L"", 0, 0, 0, 0, 0,
952 HWND_MESSAGE, nullptr, inst, nullptr);
953 if (!hwnd) {
954 std::fprintf(stderr, "[rt] gameinput: no raw mouse input (window: error %lu); using the cursor position\n",
955 GetLastError());
956 return;
957 }
958 RAWINPUTDEVICE dev{};
959 dev.usUsagePage = 0x01; // HID generic desktop
960 dev.usUsage = 0x02; // mouse
961 dev.dwFlags = RIDEV_INPUTSINK; // also while this (invisible) window has no focus; focus is checked per poll
962 dev.hwndTarget = hwnd;
963 if (!RegisterRawInputDevices(&dev, 1, sizeof(dev))) {
964 std::fprintf(stderr, "[rt] gameinput: no raw mouse input (register: error %lu); using the cursor position\n",
965 GetLastError());
966 DestroyWindow(hwnd);
967 return;
968 }
969 g_raw_ready = true;
970 std::fprintf(stderr, "[rt] gameinput: raw mouse input on (the right stick does not stop at the screen edge)\n");
971 MSG m;
972 while (GetMessageW(&m, nullptr, 0, 0) > 0) DispatchMessageW(&m);
973}
974
975void start_raw_mouse() {
976 if (!g_raw_started.exchange(true)) std::thread(raw_mouse_thread).detach();
977}
978
914bool system_cursor_pos(int* x, int* y) { 979bool system_cursor_pos(int* x, int* y) {
980 if (g_raw_ready) { // the edgeless total; it wraps only after ±2^31 counts, and the poll uses differences
981 *x = static_cast<int>(g_raw_x.load());
982 *y = static_cast<int>(g_raw_y.load());
983 return true;
984 }
915 POINT p; 985 POINT p;
916 if (!GetCursorPos(&p)) return false; 986 if (!GetCursorPos(&p)) return false;
917 *x = p.x; 987 *x = p.x;
@@ -946,6 +1016,33 @@ void detach_keyboard_pad() {
946 g_keyboard = {}; 1016 g_keyboard = {};
947} 1017}
948 1018
1019// Keeps the cursor inside the game window while it has focus, so a click cannot land on another window, and releases
1020// it on focus loss. Only with raw input (a clipped plain cursor would stop the stick at the window edge) and only for
1021// a real foreground window of this process: not KeyboardPadMode::Always over a terminal, nor a test's fake focus.
1022// Re-applied every 100 ms, because Windows drops the clip on some focus and resize changes.
1023bool g_clipped = false;
1024uint64_t g_clip_at = 0;
1025
1026void clip_cursor(bool want) {
1027 if (!want) {
1028 if (g_clipped) ClipCursor(nullptr);
1029 g_clipped = false;
1030 return;
1031 }
1032 const uint64_t now = now_us();
1033 if (g_clipped && now - g_clip_at < 100'000) return;
1034 const HWND w = GetForegroundWindow();
1035 RECT r;
1036 if (!w || !GetClientRect(w, &r)) return;
1037 POINT top_left{r.left, r.top}, bottom_right{r.right, r.bottom};
1038 if (!ClientToScreen(w, &top_left) || !ClientToScreen(w, &bottom_right)) return;
1039 const RECT screen{top_left.x, top_left.y, bottom_right.x, bottom_right.y};
1040 if (screen.right > screen.left && screen.bottom > screen.top && ClipCursor(&screen)) {
1041 g_clipped = true;
1042 g_clip_at = now;
1043 }
1044}
1045
949bool attach_keyboard_pad() { 1046bool attach_keyboard_pad() {
950 SDL_VirtualJoystickDesc d; 1047 SDL_VirtualJoystickDesc d;
951 SDL_INIT_INTERFACE(&d); 1048 SDL_INIT_INTERFACE(&d);
@@ -966,17 +1063,21 @@ bool attach_keyboard_pad() {
966 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, " 1063 std::fprintf(stderr, "[rt] gameinput: keyboard pad attached (arrows d-pad, Enter A, Backspace B, X X, Y Y, "
967 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left " 1064 "Q/E shoulders, Esc Menu, Tab View, WASD left stick, mouse right stick, right/left "
968 "button LT/RT)\n"); 1065 "button LT/RT)\n");
1066 start_raw_mouse();
969 return true; 1067 return true;
970} 1068}
971 1069
972// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading. 1070// Before SDL_UpdateGamepads, so the buttons set here are in this poll's reading.
973void update_keyboard_pad() { 1071void update_keyboard_pad() {
1072 float sens;
974 rt::gameinput::KeyboardPadMode mode; 1073 rt::gameinput::KeyboardPadMode mode;
975 { 1074 {
976 std::lock_guard lock(g().mu); 1075 std::lock_guard lock(g().mu);
977 mode = g().config.keyboard_pad; 1076 mode = g().config.keyboard_pad;
1077 sens = g().config.mouse_sensitivity;
978 } 1078 }
979 if (mode == rt::gameinput::KeyboardPadMode::Off) { 1079 if (mode == rt::gameinput::KeyboardPadMode::Off) {
1080 clip_cursor(false);
980 if (g_keyboard.id) detach_keyboard_pad(); 1081 if (g_keyboard.id) detach_keyboard_pad();
981 g_keyboard.failed = false; 1082 g_keyboard.failed = false;
982 return; 1083 return;
@@ -988,7 +1089,8 @@ void update_keyboard_pad() {
988 bool aim = false, fire = false; 1089 bool aim = false, fire = false;
989 // Out of focus every button, stick and trigger is released, so a key held while switching windows does not stay 1090 // Out of focus every button, stick and trigger is released, so a key held while switching windows does not stay
990 // pressed, and the cursor is read afresh on return, so moving it in another window does not swing the stick. 1091 // pressed, and the cursor is read afresh on return, so moving it in another window does not swing the stick.
991 if (mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()()) { 1092 const bool active = mode == rt::gameinput::KeyboardPadMode::Always || g_has_focus.load()();
1093 if (active) {
992 const rt::gameinput::KeyDownFn key_down = g_key_down.load(); 1094 const rt::gameinput::KeyDownFn key_down = g_key_down.load();
993 for (const auto& b : kKeyBindings) down[b.sdl_button] |= key_down(b.virtual_key); 1095 for (const auto& b : kKeyBindings) down[b.sdl_button] |= key_down(b.virtual_key);
994 lx = key_down('D') - key_down('A'); // opposite keys cancel 1096 lx = key_down('D') - key_down('A'); // opposite keys cancel
@@ -999,9 +1101,9 @@ void update_keyboard_pad() {
999 int x = 0, y = 0; 1101 int x = 0, y = 0;
1000 const bool have = g_cursor_pos.load()(&x, &y); 1102 const bool have = g_cursor_pos.load()(&x, &y);
1001 const bool moved = have && g_keyboard.have_cursor; 1103 const bool moved = have && g_keyboard.have_cursor;
1002 auto step = [](int v, int pixels) { 1104 auto step = [sens](int v, int pixels) {
1003 const long long n = static_cast<long long>(v) * kMouseDecayNum / kMouseDecayDen + 1105 const long long n = static_cast<long long>(v) * kMouseDecayNum / kMouseDecayDen +
1004 static_cast<long long>(pixels) * kMouseAxisPerPixel; 1106 std::lround(static_cast<long long>(pixels) * kMouseAxisPerPixel * sens);
1005 return static_cast<int>(std::clamp<long long>(n, -kStickFull, kStickFull)); 1107 return static_cast<int>(std::clamp<long long>(n, -kStickFull, kStickFull));
1006 }; 1108 };
1007 g_keyboard.right_x = step(g_keyboard.right_x, moved ? x - g_keyboard.cursor_x : 0); 1109 g_keyboard.right_x = step(g_keyboard.right_x, moved ? x - g_keyboard.cursor_x : 0);
@@ -1012,6 +1114,7 @@ void update_keyboard_pad() {
1012 g_keyboard.right_x = g_keyboard.right_y = 0; 1114 g_keyboard.right_x = g_keyboard.right_y = 0;
1013 g_keyboard.have_cursor = false; 1115 g_keyboard.have_cursor = false;
1014 } 1116 }
1117 clip_cursor(active && g_raw_ready && g_cursor_pos.load() == system_cursor_pos && foreground_is_ours());
1015 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]); 1118 for (const auto& b : kKeyBindings) SDL_SetJoystickVirtualButton(g_keyboard.js, b.sdl_button, down[b.sdl_button]);
1016 const int reach = lx && ly ? kStickDiagonal : kStickFull; 1119 const int reach = lx && ly ? kStickDiagonal : kStickFull;
1017 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach)); 1120 SDL_SetJoystickVirtualAxis(g_keyboard.js, SDL_GAMEPAD_AXIS_LEFTX, static_cast<Sint16>(lx * reach));
@@ -1225,10 +1328,12 @@ HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* de
1225 if (device) { 1328 if (device) {
1226 Device* dev = as_device(device); 1329 Device* dev = as_device(device);
1227 if (dev->info.deviceFamily == GameInputFamilyAggregate) { 1330 if (dev->info.deviceFamily == GameInputFamilyAggregate) {
1228 const uint32_t effective_kind = (kind != GameInputKindUnknown) ? kind : dev->info.supportedInput; 1331 if (kind != GameInputKindUnknown && !(kind & dev->info.supportedInput))
1332 return GAMEINPUT_E_READING_NOT_FOUND;
1333 const uint32_t effective_kind = (kind != GameInputKindUnknown) ? (kind & dev->info.supportedInput) : dev->info.supportedInput;
1229 scope.clear(); 1334 scope.clear();
1230 for (Device* cd : s.connected) { 1335 for (Device* cd : s.connected) {
1231 if (effective_kind == GameInputKindUnknown || (effective_kind & cd->info.supportedInput)) { 1336 if (effective_kind & cd->info.supportedInput) {
1232 scope.push_back(cd); 1337 scope.push_back(cd);
1233 } 1338 }
1234 } 1339 }
@@ -1281,9 +1386,11 @@ public:
1281 if (device) { 1386 if (device) {
1282 Device* d = as_device(device); 1387 Device* d = as_device(device);
1283 if (d->info.deviceFamily == GameInputFamilyAggregate) { 1388 if (d->info.deviceFamily == GameInputFamilyAggregate) {
1284 const uint32_t effective_kind = (kind != GameInputKindUnknown) ? kind : d->info.supportedInput; 1389 if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput))
1390 return GAMEINPUT_E_READING_NOT_FOUND;
1391 const uint32_t effective_kind = (kind != GameInputKindUnknown) ? (kind & d->info.supportedInput) : d->info.supportedInput;
1285 for (Device* cd : g().connected) { 1392 for (Device* cd : g().connected) {
1286 if (effective_kind != GameInputKindUnknown && !(effective_kind & cd->info.supportedInput)) continue; 1393 if (!(effective_kind & cd->info.supportedInput)) continue;
1287 if (Reading* r = cd->latest(); r && (!best || r->GetTimestamp() >= best->GetTimestamp())) best = r; 1394 if (Reading* r = cd->latest(); r && (!best || r->GetTimestamp() >= best->GetTimestamp())) best = r;
1288 } 1395 }
1289 } else { 1396 } else {
@@ -1310,6 +1417,8 @@ public:
1310 IGameInputReading** out) override { 1417 IGameInputReading** out) override {
1311 return find_reading(ref, kind, device, out, false); 1418 return find_reading(ref, kind, device, out, false);
1312 } 1419 }
1420 // E_NOTIMPL is GameInput v0's own answer: Microsoft's reference page says the method "was never implemented in
1421 // v0" and returns E_NOTIMPL, and v1 removed it. A history lookup here would give a title what no GameInput does.
1313 HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t, IGameInputDevice*, IGameInputReading** out) override { 1422 HRESULT STDMETHODCALLTYPE GetTemporalReading(uint64_t, IGameInputDevice*, IGameInputReading** out) override {
1314 if (!out) return E_POINTER; 1423 if (!out) return E_POINTER;
1315 *out = nullptr; 1424 *out = nullptr;
@@ -1318,6 +1427,9 @@ public:
1318 1427
1319 HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice* device, uint32_t kind, float, void* context, 1428 HRESULT STDMETHODCALLTYPE RegisterReadingCallback(IGameInputDevice* device, uint32_t kind, float, void* context,
1320 GameInputReadingCallback fn, GameInputCallbackToken* token) override { 1429 GameInputReadingCallback fn, GameInputCallbackToken* token) override {
1430 if (token) *token = kInvalidCallbackToken;
1431 if (!fn) return E_INVALIDARG;
1432 if (device && as_device(device)->info.deviceFamily == GameInputFamilyAggregate) return E_NOTIMPL;
1321 return add({0, CbType::Reading, as_device(device), kind, 0, context, reinterpret_cast<void*>(fn), true}, token); 1433 return add({0, CbType::Reading, as_device(device), kind, 0, context, reinterpret_cast<void*>(fn), true}, token);
1322 } 1434 }
1323 1435
@@ -1326,6 +1438,7 @@ public:
1326 GameInputDeviceCallback fn, GameInputCallbackToken* token) override { 1438 GameInputDeviceCallback fn, GameInputCallbackToken* token) override {
1327 if (token) *token = kInvalidCallbackToken; 1439 if (token) *token = kInvalidCallbackToken;
1328 if (!fn) return E_INVALIDARG; 1440 if (!fn) return E_INVALIDARG;
1441 if (device && as_device(device)->info.deviceFamily == GameInputFamilyAggregate) return E_NOTIMPL;
1329 State& s = g(); 1442 State& s = g();
1330 GameInputCallbackToken t; 1443 GameInputCallbackToken t;
1331 std::vector<Event> now; 1444 std::vector<Event> now;