Compare commits

..
Author SHA1 Message Date
ates 147888c125 GameInput: expose a keyboard-backed gamepad
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-30 00:46:24 +03:00
7 changed files with 569 additions and 22 deletions

No files matched your search

+1
View File
@@ -27,6 +27,7 @@ remains unsupported.
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
### Added
- `GameInput.dll` exposes one keyboard-backed gamepad through v0 blocking enumeration and current readings. Enter or Space maps to A, Escape or Backspace to B, arrow keys to the D-pad, WASD and IJKL to the two sticks, Q/E to shoulders, Z/C to triggers, F/H to stick clicks, X/Y to the matching face buttons, and P/Tab to Menu/View. Input returns to neutral when another application owns the foreground.
- `xgameruntime.dll` serves `XGameSaveGetContainerInfo` (slot 13) and `XGameSaveEnumerateContainerInfoByName` (slot 15) on `IXGameSaveImpl` (#667). `XGameSaveGetContainerInfo` reads container metadata without loading blob payloads and, when the named container does not exist, succeeds without invoking the callback (source rank 3 inference). `XGameSaveEnumerateContainerInfoByName` filters containers by name prefix (treating `nullptr` or empty prefix as all containers), sorts by name, and stops early when the callback returns `false`. `test_xgameruntime_saves` checks both slots through `QueryApiImpl`.
- `xgameruntime.dll` serves `XAsyncRun`, `XTaskQueueCreateComposite`, `XTaskQueueGetPort` and `XTaskQueueDuplicateHandle` through `IXGameRuntimeCore` slots 6, 13, 14 and 15 (#666). `XAsyncRun` runs the title's work callback on the block's work port and completes the block with its result. A duplicated queue handle shares the queue, and only the last close shuts its lanes down. A composite queue forwards each port to the port it was made from, and an async block's completion returns through the queue the block named. A project-authorized target build uses these for its save-game work and exited when `XAsyncRun` was unimplemented. `test_xgameruntime` checks all four through `QueryApiImpl`.
- `bx-cli report <log.jsonl>...` (#664, part 1): a run report per log (one log is one run) and a summary across runs. Per run: how it ended, the frames presented (a lower bound), every unimplemented call with its count, faults whose innermost frame is in a BetterXen module, and pipelines by kind. The summary counts clean runs and lists each blocker signature with the number of runs that hit it; blocker issues are titled with those signatures. `bx-cli run` now appends a `run_end` record to its log (exited with a status, timeout, signal or launch failure), which the report reads. A log without it has an unknown outcome and is never counted as clean.
+2 -1
View File
@@ -1,4 +1,5 @@
bx_add_shim_dll(gameinput GameInput GameInput.def
gameinput.cpp
keyboard_gamepad.cpp
)
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32)
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32 user32)
+56 -21
View File
@@ -7,16 +7,19 @@
#include <unordered_map>
#include "bx_log.h"
#include "keyboard_gamepad.h"
namespace {
// GameInputCreate @1 exposes the legacy v0 COM layout.
constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
using Callback = void (WINAPI*)();
using DeviceCallback = void (WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
// GameInputEnumerationKind values from Microsoft's public GDK GameInput (v0) reference:
// 0 = GameInputNoEnumeration, 1 = GameInputAsyncEnumeration, 2 = GameInputBlockingEnumeration.
constexpr uint32_t kMaxEnumerationKind = 2;
constexpr uint32_t kAsyncEnumeration = 1;
constexpr uint32_t kBlockingEnumeration = 2;
struct SrwExclusiveLock {
explicit SrwExclusiveLock(SRWLOCK& lock) : lock_(lock) { AcquireSRWLockExclusive(&lock_); }
@@ -34,7 +37,7 @@ struct RegisteredDeviceCallback {
uint32_t status_filter = 0;
uint32_t enumeration_kind = 0;
void* context = nullptr;
Callback callback = nullptr;
DeviceCallback callback = nullptr;
bool stopped = false;
};
@@ -91,9 +94,15 @@ public:
virtual uint64_t WINAPI GetCurrentTimestamp() {
return GetTickCount64() * 1000;
}
virtual HRESULT WINAPI GetCurrentReading(uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading");
return unavailable(out);
virtual HRESULT WINAPI GetCurrentReading(uint32_t kind, void* device, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!(kind & keyboard_gamepad::input_kind)) {
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading(non-gamepad)");
return E_NOTIMPL;
}
if (device && device != keyboard_gamepad::device()) return keyboard_gamepad::device_not_found;
return keyboard_gamepad::read(out);
}
virtual HRESULT WINAPI GetNextReading(void*, uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 5, "GetNextReading");
@@ -117,25 +126,45 @@ public:
uint32_t status_filter,
uint32_t enumeration_kind,
void* context,
Callback callback,
DeviceCallback callback,
uint64_t* out_token
) {
if (out_token) *out_token = 0;
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kMaxEnumerationKind) {
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kBlockingEnumeration) {
return E_INVALIDARG;
}
SrwExclusiveLock guard(callback_lock_);
const uint64_t token = next_token_++;
callbacks_.emplace(token, RegisteredDeviceCallback{
device,
input_kind,
status_filter,
enumeration_kind,
context,
callback,
false,
});
uint64_t token;
{
SrwExclusiveLock guard(callback_lock_);
token = next_token_++;
callbacks_.emplace(token, RegisteredDeviceCallback{
device,
input_kind,
status_filter,
enumeration_kind,
context,
callback,
false,
});
}
if (out_token) *out_token = token;
auto* pad = keyboard_gamepad::device();
const bool matches = (!device || device == pad) &&
(input_kind & keyboard_gamepad::input_kind) &&
(status_filter & keyboard_gamepad::device_status);
if (matches && enumeration_kind == kBlockingEnumeration) {
// The title requests blocking enumeration. The callback may reenter
// GameInput, so never call it under the registration lock.
static std::atomic_flag reported;
if (!reported.test_and_set(std::memory_order_relaxed)) {
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_connected",
"keyboard gamepad announced through v0 device enumeration");
}
callback(token, context, pad, GetCurrentTimestamp(), keyboard_gamepad::device_status, 0);
} else if (matches && enumeration_kind == kAsyncEnumeration) {
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback(async gamepad enumeration)");
}
return S_OK;
}
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
@@ -166,9 +195,15 @@ public:
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromId(const void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 16, "FindDeviceFromId");
return unavailable(out);
virtual HRESULT WINAPI FindDeviceFromId(const void* id, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!id) return E_INVALIDARG;
if (!keyboard_gamepad::has_id(id)) return keyboard_gamepad::device_not_found;
auto* pad = keyboard_gamepad::device();
pad->AddRef();
*out = pad;
return S_OK;
}
virtual HRESULT WINAPI FindDeviceFromObject(IUnknown*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 17, "FindDeviceFromObject");
+306
View File
@@ -0,0 +1,306 @@
#include "keyboard_gamepad.h"
#include <array>
#include <atomic>
#include <cstddef>
#include <cstring>
#include <new>
#include "bx_log.h"
namespace keyboard_gamepad {
namespace {
// Legacy GameInput v0 interface identities and Win64 data layouts.
constexpr GUID device_iid = {0x31dd86fb, 0x4c1b, 0x408a, {0x86, 0x8f, 0x43, 0x9b, 0x3c, 0xd4, 0x71, 0x25}};
constexpr GUID reading_iid = {0x2156947a, 0xe1fa, 0x4de0, {0xa3, 0x0b, 0xd8, 0x12, 0x93, 0x1d, 0xbd, 0x8d}};
struct GamepadState {
uint32_t buttons;
float left_trigger;
float right_trigger;
float left_x;
float left_y;
float right_x;
float right_y;
};
static_assert(sizeof(GamepadState) == 28);
struct BatteryState {
float rate, max_rate, remaining, capacity;
uint32_t status;
};
static_assert(sizeof(BatteryState) == 20);
struct DeviceString {
uint32_t bytes;
uint32_t code_points;
const char* text;
};
using DeviceId = std::array<uint8_t, 32>;
constexpr DeviceId device_id{{'B', 'e', 't', 't', 'e', 'r', 'X', 'e', 'n', '-', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd'}};
constexpr char device_name[] = "BetterXen Keyboard Gamepad";
constexpr DeviceString display_name{
sizeof(device_name) - 1, sizeof(device_name) - 1, device_name,
};
// Menu, View, A/B/X/Y, D-pad, shoulders, and stick clicks, in v0 label order.
constexpr std::array<uint32_t, 14> gamepad_labels{{4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 17, 20}};
// The virtual device supplies only fixed-format gamepad data. The arrays group
// the zero-valued v0 metadata for raw reports, other input kinds, and motors.
struct DeviceInfo {
uint32_t size;
uint16_t vendor_id, product_id, revision;
uint8_t interface_number, collection_number;
uint16_t usage_page, usage;
uint16_t hardware_version[4], firmware_version[4];
DeviceId id, root_id;
int32_t family;
uint32_t capabilities, supported_input, supported_rumble;
uint32_t counts[12];
const void* other_input_info[12];
const uint32_t* gamepad_info;
const void* wheel_navigation_motor_info[4];
const DeviceString* display_name;
const void* device_strings;
const void* descriptor;
};
static_assert(sizeof(DeviceInfo) == 320);
static_assert(offsetof(DeviceInfo, id) == 32);
static_assert(offsetof(DeviceInfo, supported_input) == 104);
static_assert(offsetof(DeviceInfo, gamepad_info) == 256);
static_assert(offsetof(DeviceInfo, display_name) == 296);
constexpr DeviceInfo device_info{
.size = sizeof(DeviceInfo),
.vendor_id = 0,
.product_id = 0,
.revision = 0,
.interface_number = 0,
.collection_number = 0,
.usage_page = 1,
.usage = 5,
.hardware_version = {},
.firmware_version = {},
.id = device_id,
.root_id = device_id,
.family = -1, // GameInputFamilyVirtual
.capabilities = 0,
.supported_input = input_kind,
.supported_rumble = 0,
.counts = {},
.other_input_info = {},
.gamepad_info = gamepad_labels.data(),
.wheel_navigation_motor_info = {},
.display_name = &display_name,
.device_strings = nullptr,
.descriptor = nullptr,
};
#define DEVICE_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputDevice", slot, method)
#define READING_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputReading", slot, method)
class Device final : public IUnknown {
LONG refs_ = 1; // The shim owns one reference for the lifetime of the device.
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown && iid != device_iid) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
ULONG WINAPI Release() override { return InterlockedDecrement(&refs_); }
virtual const DeviceInfo* WINAPI GetDeviceInfo() { return &device_info; }
virtual uint32_t WINAPI GetDeviceStatus() { return device_status; }
virtual void WINAPI GetBatteryState(BatteryState* out) { if (out) *out = {}; }
virtual HRESULT WINAPI CreateForceFeedbackEffect(uint32_t, const void*, void** out) {
DEVICE_STUB(6, "CreateForceFeedbackEffect");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual bool WINAPI IsForceFeedbackMotorPoweredOn(uint32_t) { return false; }
virtual void WINAPI SetForceFeedbackMotorGain(uint32_t, float) { DEVICE_STUB(8, "SetForceFeedbackMotorGain"); }
virtual HRESULT WINAPI SetHapticMotorState(uint32_t, const void*) {
DEVICE_STUB(9, "SetHapticMotorState");
return E_NOTIMPL;
}
virtual void WINAPI SetRumbleState(const void*) { DEVICE_STUB(10, "SetRumbleState"); }
virtual void WINAPI SetInputSynchronizationState(bool) { DEVICE_STUB(11, "SetInputSynchronizationState"); }
virtual void WINAPI SendInputSynchronizationHint() { DEVICE_STUB(12, "SendInputSynchronizationHint"); }
virtual void WINAPI PowerOff() { DEVICE_STUB(13, "PowerOff"); }
virtual HRESULT WINAPI CreateRawDeviceReport(uint32_t, uint32_t, void** out) {
DEVICE_STUB(14, "CreateRawDeviceReport");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual HRESULT WINAPI GetRawDeviceFeature(uint32_t, void** out) {
DEVICE_STUB(15, "GetRawDeviceFeature");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual HRESULT WINAPI SetRawDeviceFeature(void*) {
DEVICE_STUB(16, "SetRawDeviceFeature");
return E_NOTIMPL;
}
virtual HRESULT WINAPI SendRawDeviceOutput(void*) {
DEVICE_STUB(17, "SendRawDeviceOutput");
return E_NOTIMPL;
}
virtual HRESULT WINAPI SendRawDeviceOutputWithResponse(void*, void** out) {
DEVICE_STUB(18, "SendRawDeviceOutputWithResponse");
if (out) *out = nullptr;
return E_NOTIMPL;
}
virtual HRESULT WINAPI ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* out) {
DEVICE_STUB(19, "ExecuteRawDeviceIoControl");
if (out) *out = 0;
return E_NOTIMPL;
}
virtual bool WINAPI AcquireExclusiveRawDeviceAccess(uint64_t) {
DEVICE_STUB(20, "AcquireExclusiveRawDeviceAccess");
return false;
}
virtual void WINAPI ReleaseExclusiveRawDeviceAccess() { DEVICE_STUB(21, "ReleaseExclusiveRawDeviceAccess"); }
};
Device virtual_device;
bool pressed(int key) { return (GetAsyncKeyState(key) & 0x8000) != 0; }
bool owns_foreground() {
const HWND foreground = GetForegroundWindow();
DWORD pid = 0;
return foreground && GetWindowThreadProcessId(foreground, &pid) && pid == GetCurrentProcessId();
}
void sample_stick(int left, int right, int down, int up, float& x, float& y) {
x = static_cast<float>(pressed(right) - pressed(left));
y = static_cast<float>(pressed(up) - pressed(down));
if (x != 0 && y != 0) {
constexpr float diagonal = 0.70710678f;
x *= diagonal;
y *= diagonal;
}
}
GamepadState sample_keyboard() {
GamepadState state{};
if (!owns_foreground()) return state;
constexpr struct KeyBinding { int key; uint32_t button; } buttons[] = {
{'P', 0x1}, {VK_TAB, 0x2}, {VK_RETURN, 0x4}, {VK_SPACE, 0x4},
{VK_ESCAPE, 0x8}, {VK_BACK, 0x8}, {'X', 0x10}, {'Y', 0x20},
{VK_UP, 0x40}, {VK_DOWN, 0x80}, {VK_LEFT, 0x100}, {VK_RIGHT, 0x200},
{'Q', 0x400}, {'E', 0x800}, {'F', 0x1000}, {'H', 0x2000},
};
for (const auto& binding : buttons) {
if (pressed(binding.key)) state.buttons |= binding.button;
}
state.left_trigger = pressed('Z') ? 1.0f : 0.0f;
state.right_trigger = pressed('C') ? 1.0f : 0.0f;
sample_stick('A', 'D', 'S', 'W', state.left_x, state.left_y);
sample_stick('J', 'L', 'K', 'I', state.right_x, state.right_y);
return owns_foreground() ? state : GamepadState{};
}
struct Sample {
GamepadState state{};
uint64_t sequence = 0;
uint64_t timestamp = 0;
};
SRWLOCK sample_lock = SRWLOCK_INIT;
Sample latest;
Sample sample() {
AcquireSRWLockExclusive(&sample_lock);
const GamepadState state = sample_keyboard();
if (!latest.sequence || std::memcmp(&state, &latest.state, sizeof(state)) != 0) {
latest = {state, latest.sequence + 1, GetTickCount64() * 1000};
}
const Sample snapshot = latest;
ReleaseSRWLockExclusive(&sample_lock);
return snapshot;
}
class Reading final : public IUnknown {
LONG refs_ = 1;
const Sample sample_;
public:
explicit Reading(const Sample& value) : sample_(value) {}
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown && iid != reading_iid) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
ULONG WINAPI Release() override {
const auto left = InterlockedDecrement(&refs_);
if (!left) delete this;
return left;
}
virtual uint32_t WINAPI GetInputKind() { return input_kind; }
virtual uint64_t WINAPI GetSequenceNumber(uint32_t kind) { return kind & input_kind ? sample_.sequence : 0; }
virtual uint64_t WINAPI GetTimestamp() { return sample_.timestamp; }
virtual void WINAPI GetDevice(void** out) {
if (!out) return;
virtual_device.AddRef();
*out = &virtual_device;
}
virtual bool WINAPI GetRawReport(void** out) {
if (out) *out = nullptr;
return false;
}
virtual uint32_t WINAPI GetControllerAxisCount() { return 0; }
virtual uint32_t WINAPI GetControllerAxisState(uint32_t, float*) { return 0; }
virtual uint32_t WINAPI GetControllerButtonCount() { return 0; }
virtual uint32_t WINAPI GetControllerButtonState(uint32_t, bool*) { return 0; }
virtual uint32_t WINAPI GetControllerSwitchCount() { return 0; }
virtual uint32_t WINAPI GetControllerSwitchState(uint32_t, uint32_t*) { return 0; }
virtual uint32_t WINAPI GetKeyCount() { return 0; }
virtual uint32_t WINAPI GetKeyState(uint32_t, void*) { return 0; }
virtual bool WINAPI GetMouseState(void*) { READING_STUB(16, "GetMouseState"); return false; }
virtual uint32_t WINAPI GetTouchCount() { return 0; }
virtual uint32_t WINAPI GetTouchState(uint32_t, void*) { return 0; }
virtual bool WINAPI GetMotionState(void*) { READING_STUB(19, "GetMotionState"); return false; }
virtual bool WINAPI GetArcadeStickState(void*) { READING_STUB(20, "GetArcadeStickState"); return false; }
virtual bool WINAPI GetFlightStickState(void*) { READING_STUB(21, "GetFlightStickState"); return false; }
virtual bool WINAPI GetGamepadState(GamepadState* out) {
if (!out) return false;
*out = sample_.state;
static std::atomic_flag reported;
if ((out->buttons || out->left_trigger || out->right_trigger || out->left_x || out->left_y ||
out->right_x || out->right_y) && !reported.test_and_set(std::memory_order_relaxed)) {
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_input",
"guest read a non-neutral keyboard gamepad state");
}
return true;
}
virtual bool WINAPI GetRacingWheelState(void*) { READING_STUB(23, "GetRacingWheelState"); return false; }
virtual bool WINAPI GetUiNavigationState(void*) { READING_STUB(24, "GetUiNavigationState"); return false; }
};
} // namespace
IUnknown* device() { return &virtual_device; }
bool has_id(const void* id) {
return id && std::memcmp(id, device_id.data(), device_id.size()) == 0;
}
HRESULT read(void** out) {
*out = new (std::nothrow) Reading(sample());
return *out ? S_OK : E_OUTOFMEMORY;
}
} // namespace keyboard_gamepad
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
namespace keyboard_gamepad {
constexpr uint32_t input_kind = 0x00040000;
constexpr uint32_t device_status = 0x3; // connected and input enabled
constexpr HRESULT device_not_found = static_cast<HRESULT>(0x838a0002u);
IUnknown* device();
bool has_id(const void* id);
HRESULT read(void** out);
} // namespace keyboard_gamepad
@@ -0,0 +1,2 @@
add_executable(test_gameinput_keyboard main.cpp)
target_link_libraries(test_gameinput_keyboard PRIVATE kernel32 user32 uuid)
@@ -0,0 +1,185 @@
#include <windows.h>
#include <unknwn.h>
#include <array>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstring>
namespace {
constexpr uint32_t gamepad_kind = 0x00040000;
constexpr uint32_t keyboard_kind = 0x10;
constexpr uint32_t connected = 1;
constexpr uint32_t input_enabled = 2;
constexpr GUID device_iid = {0x31dd86fb, 0x4c1b, 0x408a, {0x86, 0x8f, 0x43, 0x9b, 0x3c, 0xd4, 0x71, 0x25}};
constexpr GUID reading_iid = {0x2156947a, 0xe1fa, 0x4de0, {0xa3, 0x0b, 0xd8, 0x12, 0x93, 0x1d, 0xbd, 0x8d}};
struct State {
uint32_t buttons;
float lt, rt, lx, ly, rx, ry;
};
static_assert(sizeof(State) == 28);
template <typename Fn>
Fn slot(IUnknown* object, unsigned index) {
return reinterpret_cast<Fn>((*reinterpret_cast<void***>(object))[index]);
}
using Create = HRESULT (WINAPI*)(void**);
using Current = HRESULT (WINAPI*)(IUnknown*, uint32_t, IUnknown*, IUnknown**);
using DeviceCallback = void (WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
using Register = HRESULT (WINAPI*)(IUnknown*, IUnknown*, uint32_t, uint32_t, uint32_t, void*, DeviceCallback, uint64_t*);
using Unregister = bool (WINAPI*)(IUnknown*, uint64_t, uint64_t);
using StateFn = bool (WINAPI*)(IUnknown*, State*);
using Sequence = uint64_t (WINAPI*)(IUnknown*, uint32_t);
struct Notification {
unsigned count = 0;
uint64_t token = 0;
uint64_t timestamp = 0;
uint32_t current = 0;
uint32_t previous = 0;
IUnknown* device = nullptr;
};
void WINAPI note_device(uint64_t token, void* context, IUnknown* device, uint64_t timestamp,
uint32_t current, uint32_t previous) {
auto& result = *static_cast<Notification*>(context);
result = {result.count + 1, token, timestamp, current, previous, device};
}
void pump_messages() {
MSG message;
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
bool focus_window(HWND window) {
SetForegroundWindow(window);
for (unsigned i = 0; i < 40; ++i) {
pump_messages();
if (GetForegroundWindow() == window) return true;
Sleep(10);
}
return false;
}
template <size_t N>
bool keys(const std::array<WORD, N>& bindings, bool down) {
std::array<INPUT, N> events{};
for (size_t i = 0; i < N; ++i) {
events[i].type = INPUT_KEYBOARD;
events[i].ki.wVk = bindings[i];
events[i].ki.dwFlags = down ? 0 : KEYEVENTF_KEYUP;
}
const bool ok = SendInput(static_cast<UINT>(N), events.data(), sizeof(INPUT)) == N;
for (unsigned i = 0; i < 4; ++i) {
pump_messages();
Sleep(10);
}
return ok;
}
uint32_t read_u32(const unsigned char* bytes, size_t offset) {
uint32_t value;
std::memcpy(&value, bytes + offset, sizeof(value));
return value;
}
#define REQUIRE(expr) do { if (!(expr)) { \
std::fprintf(stderr, "FAIL: GameInput keyboard line %d: %s\n", __LINE__, #expr); return 1; \
} } while (false)
} // namespace
int main() {
HMODULE module = LoadLibraryW(L"GameInput.dll");
REQUIRE(module);
const auto create = reinterpret_cast<Create>(reinterpret_cast<void*>(GetProcAddress(module, MAKEINTRESOURCEA(1))));
REQUIRE(create);
IUnknown* game_input = nullptr;
REQUIRE(create(reinterpret_cast<void**>(&game_input)) == S_OK && game_input);
const auto current = slot<Current>(game_input, 4);
const auto register_device = slot<Register>(game_input, 9);
const auto unregister = slot<Unregister>(game_input, 13);
Notification pad{};
uint64_t token = 0;
REQUIRE(register_device(game_input, nullptr, gamepad_kind, connected, 2, &pad, note_device, &token) == S_OK);
REQUIRE(pad.count == 1 && pad.token == token && pad.device && pad.timestamp);
REQUIRE(pad.current == (connected | input_enabled) && pad.previous == 0);
REQUIRE(unregister(game_input, token, 10000));
Notification filtered{};
REQUIRE(register_device(game_input, nullptr, keyboard_kind, connected, 2, &filtered, note_device, &token) == S_OK);
REQUIRE(filtered.count == 0 && unregister(game_input, token, 10000));
REQUIRE(register_device(game_input, pad.device, gamepad_kind, connected, 0, &filtered, note_device, &token) == S_OK);
REQUIRE(filtered.count == 0 && unregister(game_input, token, 10000));
void* interface_pointer = nullptr;
REQUIRE(pad.device->QueryInterface(device_iid, &interface_pointer) == S_OK && interface_pointer == pad.device);
static_cast<IUnknown*>(interface_pointer)->Release();
using Info = const unsigned char* (WINAPI*)(IUnknown*);
const auto info = slot<Info>(pad.device, 3)(pad.device);
REQUIRE(info && read_u32(info, 0) == 320 && read_u32(info, 104) == gamepad_kind);
using Find = HRESULT (WINAPI*)(IUnknown*, const void*, IUnknown**);
IUnknown* found = nullptr;
REQUIRE(slot<Find>(game_input, 16)(game_input, info + 32, &found) == S_OK && found == pad.device);
found->Release();
IUnknown* resting = nullptr;
REQUIRE(current(game_input, gamepad_kind, pad.device, &resting) == S_OK && resting);
REQUIRE(resting->QueryInterface(reading_iid, &interface_pointer) == S_OK && interface_pointer == resting);
static_cast<IUnknown*>(interface_pointer)->Release();
const auto state = slot<StateFn>(resting, 22);
const auto sequence = slot<Sequence>(resting, 4);
using GetDevice = void (WINAPI*)(IUnknown*, IUnknown**);
slot<GetDevice>(resting, 6)(resting, &found);
REQUIRE(found == pad.device);
found->Release();
State neutral{};
REQUIRE(state(resting, &neutral) && neutral.buttons == 0 && neutral.lx == 0 && neutral.rt == 0);
REQUIRE(sequence(resting, gamepad_kind) != 0 && sequence(resting, keyboard_kind) == 0);
IUnknown* invalid = resting;
REQUIRE(current(game_input, gamepad_kind, game_input, &invalid) == static_cast<HRESULT>(0x838a0002u) && !invalid);
HWND window = CreateWindowExW(0, L"STATIC", L"BetterXen keyboard conformance",
WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
300, 150, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
REQUIRE(window && focus_window(window));
const std::array<WORD, 7> bindings{VK_RETURN, VK_LEFT, 'W', 'D', 'J', 'C', 'Q'};
const bool keydown = keys(bindings, true);
IUnknown* active = nullptr;
const HRESULT active_result = current(game_input, gamepad_kind, pad.device, &active);
ShowWindow(window, SW_HIDE);
pump_messages();
IUnknown* unfocused = nullptr;
const HRESULT unfocused_result = current(game_input, gamepad_kind, pad.device, &unfocused);
const bool keyup = keys(bindings, false);
DestroyWindow(window);
REQUIRE(keydown && keyup && active_result == S_OK && active);
REQUIRE(unfocused_result == S_OK && unfocused);
State pressed{};
REQUIRE(state(active, &pressed));
REQUIRE(pressed.buttons == (0x4 | 0x100 | 0x400));
REQUIRE(pressed.lt == 0 && pressed.rt == 1);
REQUIRE(std::fabs(pressed.lx - 0.70710678f) < 0.001f && std::fabs(pressed.ly - 0.70710678f) < 0.001f);
REQUIRE(pressed.rx == -1 && pressed.ry == 0);
REQUIRE(state(resting, &neutral) && neutral.buttons == 0);
REQUIRE(state(unfocused, &neutral) && neutral.buttons == 0 && neutral.rt == 0 && neutral.lx == 0);
REQUIRE(sequence(active, gamepad_kind) > sequence(resting, gamepad_kind));
REQUIRE(sequence(unfocused, gamepad_kind) > sequence(active, gamepad_kind));
unfocused->Release();
active->Release();
resting->Release();
game_input->Release();
FreeLibrary(module);
std::puts("PASS: GameInput v0 keyboard gamepad enumeration, state, and foreground handling");
return 0;
}