diff --git a/native/common/hook_protocol.h b/native/common/hook_protocol.h index a20c7b1..9d76d74 100644 --- a/native/common/hook_protocol.h +++ b/native/common/hook_protocol.h @@ -16,9 +16,8 @@ namespace inputsplit::proto { constexpr uint32_t kMagic = 0x4C505349; // "ISPL" in little-endian -constexpr uint16_t kProtocolVersion = 5; // 2: DirectInput / Raw Input counters, 3: frame stats, - // 4: tuning (dead zones, button remapping), - // 5: player order in tuning +constexpr uint16_t kProtocolVersion = 6; // 2: DirectInput / Raw Input counters, 3: frame stats, + // 4: tuning, 5: player order, 6: pad bridge // Pipe name prefix; the game PID (decimal) is appended. constexpr wchar_t kPipePrefix[] = L"\\\\.\\pipe\\InputSplit.Hook."; @@ -159,6 +158,39 @@ struct LogMessage { char text[480]; // UTF-8, zero-terminated }; +// Pad bridge: PlayStation and Nintendo controllers shown to isolated games as XInput +// controllers. The helper reads the controller (HID) and writes its state into a shared +// memory section; the hook answers XInputGetState for that slot from it and writes +// vibration requests back. One entry per XInput slot. +constexpr wchar_t kPadBridgeName[] = L"Local\\InputSplit.PadBridge"; +constexpr uint32_t kPadBridgeMagic = 0x44415042; // "BPAD" + +struct BridgedPad { + uint32_t sequence; // odd while the helper writes (read again if it changed or is odd) + uint32_t connected; // 1 while a bridged controller holds this slot + uint32_t packet; // XINPUT_STATE::dwPacketNumber + uint16_t buttons; // XINPUT_GAMEPAD layout (plus 0x0400 Guide) + uint8_t leftTrigger; + uint8_t rightTrigger; + int16_t thumbLX; + int16_t thumbLY; + int16_t thumbRX; + int16_t thumbRY; + uint16_t vendorId; + uint16_t productId; + // Written by the hook (XInputSetState), read by the helper. + uint32_t rumbleSequence; + uint16_t rumbleLeft; // low-frequency (strong) motor + uint16_t rumbleRight; // high-frequency (weak) motor + uint32_t reserved; +}; + +struct PadBridgeMemory { + uint32_t magic; + uint32_t version; // kProtocolVersion + BridgedPad slots[4]; +}; + #pragma pack(pop) static_assert(sizeof(Header) == 16, "Header layout changed"); @@ -166,6 +198,8 @@ static_assert(sizeof(HelloMessage) == 40, "HelloMessage layout changed"); static_assert(sizeof(ConfigureMessage) == 32, "ConfigureMessage layout changed"); static_assert(sizeof(FrameStatsMessage) == 24, "FrameStatsMessage layout changed"); static_assert(sizeof(TuningMessage) == 48, "TuningMessage layout changed"); +static_assert(sizeof(BridgedPad) == 40, "BridgedPad layout changed"); +static_assert(sizeof(PadBridgeMemory) == 168, "PadBridgeMemory layout changed"); static_assert(sizeof(StatusMessage) == 160, "StatusMessage layout changed"); static_assert(sizeof(LogMessage) == 504, "LogMessage layout changed"); diff --git a/native/helper/CMakeLists.txt b/native/helper/CMakeLists.txt index d71eea7..75f1a4e 100644 --- a/native/helper/CMakeLists.txt +++ b/native/helper/CMakeLists.txt @@ -6,6 +6,7 @@ add_executable(inputsplit-helper windows_enum.cpp safety.cpp controllers.cpp + pad_bridge.cpp displays.cpp audio.cpp injector.cpp diff --git a/native/helper/controllers.cpp b/native/helper/controllers.cpp index 1291f9e..9ffdeb4 100644 --- a/native/helper/controllers.cpp +++ b/native/helper/controllers.cpp @@ -16,6 +16,8 @@ extern "C" { #include #include +#include "pad_bridge.h" + namespace inputsplit::helper { namespace { @@ -246,13 +248,16 @@ Json SnapshotLocked() { for (const HidPad& pad : g_hidPads) { pads.push_back(Json{{"vendorId", pad.vendorId}, {"productId", pad.productId}}); } - return Json{{"controllers", list}, {"hidGamepads", pads}}; + return Json{{"controllers", list}, + {"hidGamepads", pads}, + {"bridged", PadBridge::Instance().List()}}; } void EmitTestState(int slot, DWORD& lastPacket, bool& wasConnected) { XINPUT_STATE state{}; GetStateFn read = g_api.getStateEx != nullptr ? g_api.getStateEx : g_api.getState; - bool connected = read(static_cast(slot), &state) == ERROR_SUCCESS; + bool connected = read(static_cast(slot), &state) == ERROR_SUCCESS || + PadBridge::Instance().Read(slot, state); if (!connected) { if (wasConnected) SendEvent("controllerState", Json{{"slot", slot}, {"connected", false}}); wasConnected = false; @@ -284,8 +289,9 @@ void PollHotkey(const bool connected[XUSER_MAX_COUNT], const bool enabled[kShort const auto now = std::chrono::steady_clock::now(); for (int slot = 0; slot < XUSER_MAX_COUNT; ++slot) { XINPUT_STATE state{}; - bool read = connected[slot] && - g_api.getState(static_cast(slot), &state) == ERROR_SUCCESS; + bool read = connected[slot] + ? g_api.getState(static_cast(slot), &state) == ERROR_SUCCESS + : PadBridge::Instance().Read(slot, state); for (size_t i = 0; i < kShortcutCount; ++i) { HotkeyTracker& tracker = trackers[slot][i]; bool pressed = enabled[i] && read && @@ -447,6 +453,16 @@ void ControllerMonitor::StartTest(int slot) { g_wake.notify_all(); } +bool ControllerMonitor::SlotConnected(int slot) { + std::lock_guard lock(g_mutex); + return slot >= 0 && slot < XUSER_MAX_COUNT && g_slots[slot].connected; +} + +void ControllerMonitor::MarkChanged() { + std::lock_guard lock(g_mutex); + SendEvent("controllersChanged", SnapshotLocked()); +} + void ControllerMonitor::MeasurePollingRate(int slot) { static std::atomic busy{false}; if (slot < 0 || slot >= XUSER_MAX_COUNT || g_api.getState == nullptr || busy.exchange(true)) { diff --git a/native/helper/controllers.h b/native/helper/controllers.h index 7e57239..e1bd24c 100644 --- a/native/helper/controllers.h +++ b/native/helper/controllers.h @@ -34,6 +34,10 @@ class ControllerMonitor { // Short vibration as feedback ("on" one pulse, "off" two, "error" three). Returns false // when XInput cannot vibrate. bool Rumble(int slot, const std::string& pattern); + // A real XInput controller is in `slot` (as of the last presence check). + bool SlotConnected(int slot); + // Sends a fresh "controllersChanged" (the pad bridge took or released a slot). + void MarkChanged(); private: ControllerMonitor() = default; diff --git a/native/helper/main.cpp b/native/helper/main.cpp index 8094f02..030cd52 100644 --- a/native/helper/main.cpp +++ b/native/helper/main.cpp @@ -25,6 +25,7 @@ #include "../common/hook_protocol.h" #include "../common/version.h" #include "controllers.h" +#include "pad_bridge.h" #include "displays.h" #include "process_info.h" #include "rpc.h" @@ -114,6 +115,10 @@ Json Handle(const std::string& method, const Json& params) { ControllerMonitor::Instance().StartTest(params.at("slot").get()); return Json::object(); } + if (method == "setPadBridge") { + PadBridge::Instance().SetEnabled(params.at("enabled").get()); + return Json{{"enabled", PadBridge::Instance().enabled()}}; + } if (method == "measurePollingRate") { ControllerMonitor::Instance().MeasurePollingRate(params.at("slot").get()); return Json::object(); @@ -304,6 +309,7 @@ int wmain(int argc, wchar_t** argv) { // stdin closed or shutdown requested: leave every game in its normal state. SessionManager::Instance().StopAll("helperShutdown", 2000); StopSystemWindow(); + PadBridge::Instance().Shutdown(); ControllerMonitor::Instance().Stop(); fflush(stdout); // Detached request threads may still be running; ExitProcess ends them cleanly. diff --git a/native/helper/pad_bridge.cpp b/native/helper/pad_bridge.cpp new file mode 100644 index 0000000..f9599e7 --- /dev/null +++ b/native/helper/pad_bridge.cpp @@ -0,0 +1,512 @@ +#include "pad_bridge.h" + +#include +// Older MinGW headers declare the HID functions without C linkage. +extern "C" { +#include +} + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../common/hook_protocol.h" +#include "controllers.h" +#include "util.h" + +namespace inputsplit::helper { +namespace { + +namespace proto = inputsplit::proto; + +constexpr uint16_t kSony = 0x054c; +constexpr uint16_t kNintendo = 0x057e; + +enum class Kind { DualShock4, DualSense, SwitchPro }; + +bool KindOf(uint16_t vendor, uint16_t product, Kind& kind) { + if (vendor == kSony) { + if (product == 0x05c4 || product == 0x09cc || product == 0x0ba0) { + kind = Kind::DualShock4; + return true; + } + if (product == 0x0ce6 || product == 0x0df2) { + kind = Kind::DualSense; + return true; + } + } + if (vendor == kNintendo && product == 0x2009) { + kind = Kind::SwitchPro; + return true; + } + return false; +} + +// HID axis 0..255 (128 = centre) to an XInput thumb value. HID Y grows downwards. +int16_t AxisX(uint8_t v) { return static_cast(v * 257 - 32768); } +int16_t AxisY(uint8_t v) { return static_cast(32767 - v * 257); } + +uint16_t Hat(uint8_t hat) { + static const uint16_t kHat[8] = { + XINPUT_GAMEPAD_DPAD_UP, + XINPUT_GAMEPAD_DPAD_UP | XINPUT_GAMEPAD_DPAD_RIGHT, + XINPUT_GAMEPAD_DPAD_RIGHT, + XINPUT_GAMEPAD_DPAD_DOWN | XINPUT_GAMEPAD_DPAD_RIGHT, + XINPUT_GAMEPAD_DPAD_DOWN, + XINPUT_GAMEPAD_DPAD_DOWN | XINPUT_GAMEPAD_DPAD_LEFT, + XINPUT_GAMEPAD_DPAD_LEFT, + XINPUT_GAMEPAD_DPAD_UP | XINPUT_GAMEPAD_DPAD_LEFT, + }; + return hat < 8 ? kHat[hat] : 0; +} + +constexpr uint16_t kGuide = 0x0400; + +// DualShock 4 layout (also DualSense's short Bluetooth report): sticks at b..b+3, hat and +// face buttons at b+4, shoulders at b+5, PS at b+6, triggers at b+7 and b+8. +void ParsePlayStation(const uint8_t* r, int b, int face, int shoulders, int ps, int l2, int r2, + XINPUT_GAMEPAD& pad) { + pad.sThumbLX = AxisX(r[b]); + pad.sThumbLY = AxisY(r[b + 1]); + pad.sThumbRX = AxisX(r[b + 2]); + pad.sThumbRY = AxisY(r[b + 3]); + const uint8_t f = r[face]; + uint16_t buttons = Hat(f & 0x0F); + if (f & 0x10) buttons |= XINPUT_GAMEPAD_X; // square + if (f & 0x20) buttons |= XINPUT_GAMEPAD_A; // cross + if (f & 0x40) buttons |= XINPUT_GAMEPAD_B; // circle + if (f & 0x80) buttons |= XINPUT_GAMEPAD_Y; // triangle + const uint8_t s = r[shoulders]; + if (s & 0x01) buttons |= XINPUT_GAMEPAD_LEFT_SHOULDER; + if (s & 0x02) buttons |= XINPUT_GAMEPAD_RIGHT_SHOULDER; + if (s & 0x10) buttons |= XINPUT_GAMEPAD_BACK; // share / create + if (s & 0x20) buttons |= XINPUT_GAMEPAD_START; // options + if (s & 0x40) buttons |= XINPUT_GAMEPAD_LEFT_THUMB; + if (s & 0x80) buttons |= XINPUT_GAMEPAD_RIGHT_THUMB; + if (r[ps] & 0x01) buttons |= kGuide; + pad.wButtons = buttons; + pad.bLeftTrigger = r[l2]; + pad.bRightTrigger = r[r2]; +} + +int16_t Stick12(int v, bool invert) { + int value = (v - 2048) * 16; + if (invert) value = -value; + return static_cast(std::clamp(value, -32768, 32767)); +} + +// Switch Pro: the full report 0x30 (after a driver such as Steam switched it on) or the +// simple HID report 0x3F (default over Bluetooth). Buttons follow their position, so the +// bottom button (B on a Switch controller) is A, like on an Xbox controller. +bool ParseSwitch(const uint8_t* r, DWORD n, XINPUT_GAMEPAD& pad) { + uint16_t buttons = 0; + if (r[0] == 0x30 && n >= 12) { + const uint8_t right = r[3], mid = r[4], left = r[5]; + if (right & 0x01) buttons |= XINPUT_GAMEPAD_X; // Y + if (right & 0x02) buttons |= XINPUT_GAMEPAD_Y; // X + if (right & 0x04) buttons |= XINPUT_GAMEPAD_A; // B + if (right & 0x08) buttons |= XINPUT_GAMEPAD_B; // A + if (right & 0x40) buttons |= XINPUT_GAMEPAD_RIGHT_SHOULDER; + if (mid & 0x01) buttons |= XINPUT_GAMEPAD_BACK; + if (mid & 0x02) buttons |= XINPUT_GAMEPAD_START; + if (mid & 0x04) buttons |= XINPUT_GAMEPAD_RIGHT_THUMB; + if (mid & 0x08) buttons |= XINPUT_GAMEPAD_LEFT_THUMB; + if (mid & 0x10) buttons |= kGuide; + if (left & 0x01) buttons |= XINPUT_GAMEPAD_DPAD_DOWN; + if (left & 0x02) buttons |= XINPUT_GAMEPAD_DPAD_UP; + if (left & 0x04) buttons |= XINPUT_GAMEPAD_DPAD_RIGHT; + if (left & 0x08) buttons |= XINPUT_GAMEPAD_DPAD_LEFT; + if (left & 0x40) buttons |= XINPUT_GAMEPAD_LEFT_SHOULDER; + pad.bRightTrigger = (right & 0x80) ? 255 : 0; // ZR + pad.bLeftTrigger = (left & 0x80) ? 255 : 0; // ZL + pad.sThumbLX = Stick12(r[6] | ((r[7] & 0x0F) << 8), false); + pad.sThumbLY = Stick12((r[7] >> 4) | (r[8] << 4), false); + pad.sThumbRX = Stick12(r[9] | ((r[10] & 0x0F) << 8), false); + pad.sThumbRY = Stick12((r[10] >> 4) | (r[11] << 4), false); + } else if (r[0] == 0x3F && n >= 12) { + const uint8_t a = r[1], b = r[2]; + if (a & 0x01) buttons |= XINPUT_GAMEPAD_A; // B + if (a & 0x02) buttons |= XINPUT_GAMEPAD_B; // A + if (a & 0x04) buttons |= XINPUT_GAMEPAD_X; // Y + if (a & 0x08) buttons |= XINPUT_GAMEPAD_Y; // X + if (a & 0x10) buttons |= XINPUT_GAMEPAD_LEFT_SHOULDER; + if (a & 0x20) buttons |= XINPUT_GAMEPAD_RIGHT_SHOULDER; + pad.bLeftTrigger = (a & 0x40) ? 255 : 0; + pad.bRightTrigger = (a & 0x80) ? 255 : 0; + if (b & 0x01) buttons |= XINPUT_GAMEPAD_BACK; + if (b & 0x02) buttons |= XINPUT_GAMEPAD_START; + if (b & 0x04) buttons |= XINPUT_GAMEPAD_LEFT_THUMB; + if (b & 0x08) buttons |= XINPUT_GAMEPAD_RIGHT_THUMB; + if (b & 0x10) buttons |= kGuide; + buttons |= Hat(r[3]); + auto u16 = [&](int i) { return static_cast(r[i] | (r[i + 1] << 8)); }; + pad.sThumbLX = static_cast(u16(4) - 32768); + pad.sThumbLY = static_cast(32767 - u16(6)); + pad.sThumbRX = static_cast(u16(8) - 32768); + pad.sThumbRY = static_cast(32767 - u16(10)); + } else { + return false; + } + pad.wButtons = buttons; + return true; +} + +bool ParseReport(Kind kind, bool bluetooth, const uint8_t* r, DWORD n, XINPUT_GAMEPAD& pad) { + if (n < 10) return false; + switch (kind) { + case Kind::DualShock4: + if (r[0] == 0x01) ParsePlayStation(r, 1, 5, 6, 7, 8, 9, pad); + else if (r[0] == 0x11 && n >= 12) ParsePlayStation(r, 3, 7, 8, 9, 10, 11, pad); + else return false; + return true; + case Kind::DualSense: + if (r[0] == 0x01 && !bluetooth && n >= 11) { + ParsePlayStation(r, 1, 8, 9, 10, 5, 6, pad); + } else if (r[0] == 0x01) { + ParsePlayStation(r, 1, 5, 6, 7, 8, 9, pad); // short Bluetooth report + } else if (r[0] == 0x31 && n >= 12) { + ParsePlayStation(r, 2, 9, 10, 11, 6, 7, pad); + } else { + return false; + } + return true; + case Kind::SwitchPro: + return ParseSwitch(r, n, pad); + } + return false; +} + +struct Device { + std::wstring path; + Kind kind = Kind::DualShock4; + bool bluetooth = false; + uint16_t vendorId = 0; + uint16_t productId = 0; + int slot = -1; + UniqueHandle handle; + DWORD inputLength = 0; + DWORD outputLength = 0; + std::atomic stop{false}; + std::thread thread; +}; + +std::mutex g_mutex; +std::atomic g_enabled{false}; +std::thread g_scanner; +std::vector> g_devices; +UniqueHandle g_section; +proto::PadBridgeMemory* g_memory = nullptr; + +bool EnsureMemory() { + if (g_memory != nullptr) return true; + HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, + sizeof(proto::PadBridgeMemory), proto::kPadBridgeName); + if (section == nullptr) return false; + void* view = + MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(proto::PadBridgeMemory)); + if (view == nullptr) { + CloseHandle(section); + return false; + } + g_section.reset(section); + g_memory = static_cast(view); + std::memset(g_memory, 0, sizeof(*g_memory)); + g_memory->magic = proto::kPadBridgeMagic; + g_memory->version = proto::kProtocolVersion; + return true; +} + +void Publish(int slot, bool connected, const XINPUT_GAMEPAD* pad, const Device* device) { + if (g_memory == nullptr || slot < 0 || slot > 3) return; + proto::BridgedPad& entry = g_memory->slots[slot]; + auto* sequence = reinterpret_cast(&entry.sequence); + InterlockedIncrement(sequence); // odd: writing + entry.connected = connected ? 1 : 0; + if (pad != nullptr) { + entry.packet++; + entry.buttons = pad->wButtons; + entry.leftTrigger = pad->bLeftTrigger; + entry.rightTrigger = pad->bRightTrigger; + entry.thumbLX = pad->sThumbLX; + entry.thumbLY = pad->sThumbLY; + entry.thumbRX = pad->sThumbRX; + entry.thumbRY = pad->sThumbRY; + } + if (device != nullptr) { + entry.vendorId = device->vendorId; + entry.productId = device->productId; + } + InterlockedIncrement(sequence); // even: done +} + +// Vibration over USB. Bluetooth needs a checksummed report and is not sent yet. +void SendRumble(Device& device, uint16_t left, uint16_t right) { + if (device.bluetooth || device.kind == Kind::SwitchPro || device.outputLength == 0) return; + std::vector report(device.outputLength, 0); + if (device.kind == Kind::DualShock4 && report.size() >= 6) { + report[0] = 0x05; + report[1] = 0x01; // motors only + report[4] = static_cast(right >> 8); + report[5] = static_cast(left >> 8); + } else if (device.kind == Kind::DualSense && report.size() >= 5) { + report[0] = 0x02; + report[1] = 0x03; // rumble emulation + motors + report[3] = static_cast(right >> 8); + report[4] = static_cast(left >> 8); + } else { + return; + } + OVERLAPPED overlapped{}; + UniqueHandle event(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + overlapped.hEvent = event.get(); + DWORD written = 0; + if (!WriteFile(device.handle.get(), report.data(), static_cast(report.size()), nullptr, + &overlapped) && + GetLastError() == ERROR_IO_PENDING) { + if (WaitForSingleObject(event.get(), 100) != WAIT_OBJECT_0) { + CancelIoEx(device.handle.get(), &overlapped); + } + GetOverlappedResult(device.handle.get(), &overlapped, &written, TRUE); + } +} + +void ReadLoop(Device* device) { + std::vector buffer(device->inputLength); + UniqueHandle event(CreateEventW(nullptr, TRUE, FALSE, nullptr)); + uint32_t lastRumble = 0; + while (!device->stop) { + OVERLAPPED overlapped{}; + overlapped.hEvent = event.get(); + ResetEvent(event.get()); + DWORD bytes = 0; + bool ok = ReadFile(device->handle.get(), buffer.data(), static_cast(buffer.size()), + nullptr, &overlapped) != FALSE; + if (!ok && GetLastError() != ERROR_IO_PENDING) break; // unplugged + while (!device->stop && WaitForSingleObject(event.get(), 20) == WAIT_TIMEOUT) { + if (g_memory != nullptr && device->slot >= 0) { + proto::BridgedPad& entry = g_memory->slots[device->slot]; + if (entry.rumbleSequence != lastRumble) { + lastRumble = entry.rumbleSequence; + SendRumble(*device, entry.rumbleLeft, entry.rumbleRight); + } + } + } + if (device->stop) { + CancelIoEx(device->handle.get(), &overlapped); + GetOverlappedResult(device->handle.get(), &overlapped, &bytes, TRUE); + break; + } + if (!GetOverlappedResult(device->handle.get(), &overlapped, &bytes, FALSE)) break; + XINPUT_GAMEPAD pad{}; + if (ParseReport(device->kind, device->bluetooth, buffer.data(), bytes, pad)) { + Publish(device->slot, true, &pad, nullptr); + } + if (g_memory != nullptr && device->slot >= 0) { + proto::BridgedPad& entry = g_memory->slots[device->slot]; + if (entry.rumbleSequence != lastRumble) { + lastRumble = entry.rumbleSequence; + SendRumble(*device, entry.rumbleLeft, entry.rumbleRight); + } + } + } + device->stop = true; // the scanner removes it +} + +struct Found { + std::wstring path; + uint16_t vendorId; + uint16_t productId; +}; + +std::vector FindControllers() { + std::vector found; + GUID hidGuid; + HidD_GetHidGuid(&hidGuid); + HDEVINFO set = + SetupDiGetClassDevsW(&hidGuid, nullptr, nullptr, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); + if (set == INVALID_HANDLE_VALUE) return found; + SP_DEVICE_INTERFACE_DATA iface{}; + iface.cbSize = sizeof(iface); + for (DWORD i = 0; SetupDiEnumDeviceInterfaces(set, nullptr, &hidGuid, i, &iface); ++i) { + DWORD size = 0; + SetupDiGetDeviceInterfaceDetailW(set, &iface, nullptr, 0, &size, nullptr); + if (size == 0) continue; + std::vector storage(size); + auto* detail = reinterpret_cast(storage.data()); + detail->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_W); + if (!SetupDiGetDeviceInterfaceDetailW(set, &iface, detail, size, nullptr, nullptr)) continue; + HANDLE probe = CreateFileW(detail->DevicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + OPEN_EXISTING, 0, nullptr); + if (probe == INVALID_HANDLE_VALUE) continue; + HIDD_ATTRIBUTES attributes{}; + attributes.Size = sizeof(attributes); + Kind kind = Kind::DualShock4; + if (HidD_GetAttributes(probe, &attributes) && + KindOf(attributes.VendorID, attributes.ProductID, kind)) { + found.push_back({detail->DevicePath, attributes.VendorID, attributes.ProductID}); + } + CloseHandle(probe); + } + SetupDiDestroyDeviceInfoList(set); + return found; +} + +bool OpenDevice(Device& device) { + HANDLE handle = CreateFileW(device.path.c_str(), GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, + FILE_FLAG_OVERLAPPED, nullptr); + if (handle == INVALID_HANDLE_VALUE) { + // Read-only still gives input (no vibration). + handle = CreateFileW(device.path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); + } + if (handle == INVALID_HANDLE_VALUE) return false; + device.handle.reset(handle); + PHIDP_PREPARSED_DATA preparsed = nullptr; + if (!HidD_GetPreparsedData(handle, &preparsed)) return false; + HIDP_CAPS caps{}; + bool ok = HidP_GetCaps(preparsed, &caps) == HIDP_STATUS_SUCCESS; + HidD_FreePreparsedData(preparsed); + if (!ok || caps.InputReportByteLength == 0) return false; + device.inputLength = caps.InputReportByteLength; + device.outputLength = caps.OutputReportByteLength; + // Bluetooth HID paths carry the HID-over-Bluetooth service id. + std::wstring lower = ToLower(device.path); + device.bluetooth = lower.find(L"00001124-0000-1000-8000-00805f9b34fb") != std::wstring::npos; + return true; +} + +void Scan() { + // XInput slots first, without our lock (see SlotConnected). + bool taken[4]; + for (int slot = 0; slot < 4; ++slot) { + taken[slot] = ControllerMonitor::Instance().SlotConnected(slot); + } + std::vector found = FindControllers(); + bool changed = false; + { + std::lock_guard lock(g_mutex); + // Drop controllers whose reader stopped (unplugged). + for (auto it = g_devices.begin(); it != g_devices.end();) { + Device& device = **it; + bool present = std::any_of(found.begin(), found.end(), + [&](const Found& f) { return f.path == device.path; }); + if (device.stop || !present) { + device.stop = true; + if (device.thread.joinable()) device.thread.join(); + Publish(device.slot, false, nullptr, nullptr); + it = g_devices.erase(it); + changed = true; + } else { + ++it; + } + } + for (const auto& device : g_devices) taken[device->slot] = true; + for (const Found& f : found) { + bool known = std::any_of(g_devices.begin(), g_devices.end(), + [&](const auto& d) { return d->path == f.path; }); + if (known) continue; + int slot = -1; + for (int s = 0; s < 4 && slot < 0; ++s) { + if (!taken[s]) slot = s; + } + if (slot < 0) break; // every XInput slot is in use + auto device = std::make_unique(); + device->path = f.path; + device->vendorId = f.vendorId; + device->productId = f.productId; + KindOf(f.vendorId, f.productId, device->kind); + if (!OpenDevice(*device)) continue; // hidden or held exclusively by another program + device->slot = slot; + taken[slot] = true; + Publish(slot, true, nullptr, device.get()); + device->thread = std::thread(ReadLoop, device.get()); + g_devices.push_back(std::move(device)); + changed = true; + } + } + if (changed) ControllerMonitor::Instance().MarkChanged(); +} + +void StopAllLocked() { + for (auto& device : g_devices) { + device->stop = true; + if (device->thread.joinable()) device->thread.join(); + Publish(device->slot, false, nullptr, nullptr); + } + g_devices.clear(); +} + +} // namespace + +PadBridge& PadBridge::Instance() { + static PadBridge instance; + return instance; +} + +bool PadBridge::enabled() const { return g_enabled; } + +void PadBridge::SetEnabled(bool enabled) { + if (enabled == g_enabled.exchange(enabled)) return; + if (enabled) { + { + std::lock_guard lock(g_mutex); + if (!EnsureMemory()) { + g_enabled = false; + return; + } + } + if (g_scanner.joinable()) g_scanner.join(); + g_scanner = std::thread([] { + while (g_enabled) { + Scan(); + for (int i = 0; i < 20 && g_enabled; ++i) Sleep(100); // rescan every 2 s + } + }); + } else { + if (g_scanner.joinable()) g_scanner.join(); + { + std::lock_guard lock(g_mutex); + StopAllLocked(); + } + ControllerMonitor::Instance().MarkChanged(); + } +} + +Json PadBridge::List() { + std::lock_guard lock(g_mutex); + Json list = Json::array(); + for (const auto& device : g_devices) { + list.push_back(Json{{"slot", device->slot}, + {"vendorId", device->vendorId}, + {"productId", device->productId}}); + } + return list; +} + +bool PadBridge::Read(int slot, XINPUT_STATE& state) { + std::lock_guard lock(g_mutex); + if (g_memory == nullptr || slot < 0 || slot > 3) return false; + bool held = std::any_of(g_devices.begin(), g_devices.end(), + [&](const auto& d) { return d->slot == slot; }); + if (!held) return false; + const proto::BridgedPad& entry = g_memory->slots[slot]; + state.dwPacketNumber = entry.packet; + state.Gamepad.wButtons = entry.buttons; + state.Gamepad.bLeftTrigger = entry.leftTrigger; + state.Gamepad.bRightTrigger = entry.rightTrigger; + state.Gamepad.sThumbLX = entry.thumbLX; + state.Gamepad.sThumbLY = entry.thumbLY; + state.Gamepad.sThumbRX = entry.thumbRX; + state.Gamepad.sThumbRY = entry.thumbRY; + return true; +} + +void PadBridge::Shutdown() { SetEnabled(false); } + +} // namespace inputsplit::helper diff --git a/native/helper/pad_bridge.h b/native/helper/pad_bridge.h new file mode 100644 index 0000000..f0b8cb8 --- /dev/null +++ b/native/helper/pad_bridge.h @@ -0,0 +1,33 @@ +// pad_bridge.h — PlayStation and Nintendo controllers as XInput controllers for isolated +// games (no driver, no virtual device: only games with InputSplit's hook see them). +// +// While enabled, the bridge opens every DualShock 4, DualSense and Switch Pro controller it +// finds, gives each one an XInput slot that no real Xbox controller uses, and keeps that +// slot's state in the shared memory section the hook reads (hook_protocol.h). Vibration the +// game asks for goes back to the controller (USB only for now). +#pragma once + +#include +#include + +#include "rpc.h" + +namespace inputsplit::helper { + +class PadBridge { + public: + static PadBridge& Instance(); + + void SetEnabled(bool enabled); + bool enabled() const; + // [{slot, vendorId, productId}] for the controller list. + Json List(); + // The current state of a bridged slot (for the controller test); false if none. + bool Read(int slot, XINPUT_STATE& state); + void Shutdown(); + + private: + PadBridge() = default; +}; + +} // namespace inputsplit::helper diff --git a/native/hook/xinput_bridge.cpp b/native/hook/xinput_bridge.cpp index 38c7932..57b3f36 100644 --- a/native/hook/xinput_bridge.cpp +++ b/native/hook/xinput_bridge.cpp @@ -50,6 +50,71 @@ struct Canonical { std::atomic g_gameWantsEnabled{true}; // last value the game passed to XInputEnable +// ---- Pad bridge: PlayStation / Nintendo controllers the helper shows as XInput slots ---- +std::atomic g_bridge{nullptr}; +std::atomic g_bridgeNextTry{0}; + +proto::PadBridgeMemory* Bridge() { + proto::PadBridgeMemory* bridge = g_bridge.load(std::memory_order_acquire); + if (bridge != nullptr) return bridge; + const ULONGLONG now = GetTickCount64(); + if (now < g_bridgeNextTry.load(std::memory_order_relaxed)) return nullptr; + // Not there yet: the helper may turn the bridge on later. + g_bridgeNextTry.store(now + 2000, std::memory_order_relaxed); + HANDLE section = + OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, proto::kPadBridgeName); + if (section == nullptr) return nullptr; + void* view = MapViewOfFile(section, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, + sizeof(proto::PadBridgeMemory)); + CloseHandle(section); // the view keeps the section alive + if (view == nullptr) return nullptr; + auto* memory = static_cast(view); + if (memory->magic != proto::kPadBridgeMagic || memory->version != proto::kProtocolVersion) { + UnmapViewOfFile(view); + return nullptr; + } + proto::PadBridgeMemory* expected = nullptr; + if (!g_bridge.compare_exchange_strong(expected, memory)) { + UnmapViewOfFile(view); + return expected; + } + Log(LogLevel::Info, "Pad bridge connected"); + return memory; +} + +// Only while InputSplit isolates this game; a stopped session leaves the game as it was. +proto::BridgedPad* BridgedSlot(DWORD physical) { + if (physical > 3 || g_active.load(std::memory_order_relaxed) == 0) return nullptr; + proto::PadBridgeMemory* bridge = Bridge(); + if (bridge == nullptr || bridge->slots[physical].connected == 0) return nullptr; + return &bridge->slots[physical]; +} + +bool ReadBridged(DWORD physical, XINPUT_STATE* state) { + proto::BridgedPad* pad = BridgedSlot(physical); + if (pad == nullptr || state == nullptr) return false; + for (int attempt = 0; attempt < 4; ++attempt) { + const uint32_t before = *reinterpret_cast(&pad->sequence); + if (before & 1) continue; // the helper is writing + MemoryBarrier(); + XINPUT_STATE copy{}; + copy.dwPacketNumber = pad->packet; + copy.Gamepad.wButtons = pad->buttons; + copy.Gamepad.bLeftTrigger = pad->leftTrigger; + copy.Gamepad.bRightTrigger = pad->rightTrigger; + copy.Gamepad.sThumbLX = pad->thumbLX; + copy.Gamepad.sThumbLY = pad->thumbLY; + copy.Gamepad.sThumbRX = pad->thumbRX; + copy.Gamepad.sThumbRY = pad->thumbRY; + MemoryBarrier(); + if (*reinterpret_cast(&pad->sequence) == before) { + *state = copy; + return true; + } + } + return false; +} + // Maps the game's user index to a physical slot. Returns false if the game should see // "no controller" for this index. bool MapUserIndex(DWORD userIndex, DWORD& physical) { @@ -71,6 +136,10 @@ DWORD WINAPI DetourGetState(DWORD userIndex, XINPUT_STATE* state) { DWORD physical = 0; if (!MapUserIndex(userIndex, physical)) return ERROR_DEVICE_NOT_CONNECTED; DWORD result = g_real.getState(physical, state); + if (result != ERROR_SUCCESS && ReadBridged(physical, state)) { + result = ERROR_SUCCESS; + if (state != nullptr) state->Gamepad.wButtons &= ~0x0400; // Guide: GetStateEx only + } if (result == ERROR_SUCCESS) { ApplyTuning(state); OnControllerRead(physical, state); @@ -84,6 +153,7 @@ DWORD WINAPI DetourGetStateEx(DWORD userIndex, XINPUT_STATE* state) { if (!MapUserIndex(userIndex, physical)) return ERROR_DEVICE_NOT_CONNECTED; GetStateFn fn = g_real.getStateEx != nullptr ? g_real.getStateEx : g_real.getState; DWORD result = fn(physical, state); + if (result != ERROR_SUCCESS && ReadBridged(physical, state)) result = ERROR_SUCCESS; if (result == ERROR_SUCCESS) { ApplyTuning(state); OnControllerRead(physical, state); @@ -94,20 +164,53 @@ DWORD WINAPI DetourGetStateEx(DWORD userIndex, XINPUT_STATE* state) { DWORD WINAPI DetourSetState(DWORD userIndex, XINPUT_VIBRATION* vibration) { DWORD physical = 0; if (!MapUserIndex(userIndex, physical)) return ERROR_DEVICE_NOT_CONNECTED; - return g_real.setState(physical, vibration); + DWORD result = g_real.setState(physical, vibration); + if (result != ERROR_SUCCESS && vibration != nullptr) { + if (proto::BridgedPad* pad = BridgedSlot(physical)) { + pad->rumbleLeft = vibration->wLeftMotorSpeed; + pad->rumbleRight = vibration->wRightMotorSpeed; + MemoryBarrier(); + InterlockedIncrement(reinterpret_cast(&pad->rumbleSequence)); + result = ERROR_SUCCESS; + } + } + return result; } DWORD WINAPI DetourGetCapabilities(DWORD userIndex, DWORD flags, XINPUT_CAPABILITIES* caps) { DWORD physical = 0; if (!MapUserIndex(userIndex, physical)) return ERROR_DEVICE_NOT_CONNECTED; - return g_real.getCapabilities(physical, flags, caps); + DWORD result = g_real.getCapabilities(physical, flags, caps); + if (result != ERROR_SUCCESS && caps != nullptr && BridgedSlot(physical) != nullptr) { + // A wired Xbox gamepad with every button, both sticks and both motors. + *caps = XINPUT_CAPABILITIES{}; + caps->Type = XINPUT_DEVTYPE_GAMEPAD; + caps->SubType = XINPUT_DEVSUBTYPE_GAMEPAD; + caps->Gamepad.wButtons = 0xF3FF; + caps->Gamepad.bLeftTrigger = 0xFF; + caps->Gamepad.bRightTrigger = 0xFF; + caps->Gamepad.sThumbLX = static_cast(0xFFC0); + caps->Gamepad.sThumbLY = static_cast(0xFFC0); + caps->Gamepad.sThumbRX = static_cast(0xFFC0); + caps->Gamepad.sThumbRY = static_cast(0xFFC0); + caps->Vibration.wLeftMotorSpeed = 0xFFFF; + caps->Vibration.wRightMotorSpeed = 0xFFFF; + result = ERROR_SUCCESS; + } + return result; } DWORD WINAPI DetourGetBattery(DWORD userIndex, BYTE devType, XINPUT_BATTERY_INFORMATION* info) { DWORD physical = 0; if (!MapUserIndex(userIndex, physical)) return ERROR_DEVICE_NOT_CONNECTED; - if (g_real.getBattery == nullptr) return ERROR_DEVICE_NOT_CONNECTED; - return g_real.getBattery(physical, devType, info); + DWORD result = g_real.getBattery != nullptr ? g_real.getBattery(physical, devType, info) + : ERROR_DEVICE_NOT_CONNECTED; + if (result != ERROR_SUCCESS && info != nullptr && BridgedSlot(physical) != nullptr) { + info->BatteryType = BATTERY_TYPE_WIRED; // the helper does not read PlayStation batteries + info->BatteryLevel = BATTERY_LEVEL_FULL; + result = ERROR_SUCCESS; + } + return result; } DWORD WINAPI DetourGetKeystroke(DWORD userIndex, DWORD reserved, XINPUT_KEYSTROKE* keystroke) { diff --git a/src/main/index.ts b/src/main/index.ts index e1f613e..0046229 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -200,9 +200,18 @@ async function main(): Promise { .catch((error: unknown) => logger.warn(`Emergency hotkey: ${String(error)}`)) setGamepadHotkey(settings.get().gamepadHotkeyEnabled) setOverlayHotkey(settings.get().overlayHotkeyEnabled) + setPadBridge(settings.get().padBridge) } }) + // PlayStation and Switch controllers as Xbox controllers for isolated games. + const setPadBridge = (enabled: boolean) => { + if (backend.getState().status !== 'ready') return + void backend + .request('setPadBridge', { enabled }) + .catch((error: unknown) => logger.warn(`Pad bridge: ${String(error)}`)) + } + // Controller shortcut (LB + RB + View held): start or stop from the couch. const setGamepadHotkey = (enabled: boolean) => { if (backend.getState().status !== 'ready') return @@ -404,6 +413,7 @@ async function main(): Promise { for (const view of seats.all()) sendTuning(view, true) } if (next.blockGameBarButton !== previousSettings.blockGameBarButton) void syncGameBar() + if (next.padBridge !== previousSettings.padBridge) setPadBridge(next.padBridge) if (next.launchAtLogin !== previousSettings.launchAtLogin) applyLoginItem(next.launchAtLogin) if (next.checkForUpdates !== previousSettings.checkForUpdates) { updates.setAutomatic(app.isPackaged && next.checkForUpdates) diff --git a/src/main/native/protocol.ts b/src/main/native/protocol.ts index 4e350a3..d0944be 100644 --- a/src/main/native/protocol.ts +++ b/src/main/native/protocol.ts @@ -11,6 +11,7 @@ import { ControllerStateSchema, DisplaySchema, HidGamepadSchema, + BridgedPadSchema, LogLevelSchema, PollingRateSchema, RectSchema, @@ -28,6 +29,8 @@ const empty = z.object({}).passthrough() const ControllerListSchema = z.object({ controllers: z.array(ControllerSchema), hidGamepads: z.array(HidGamepadSchema).optional(), + /** PlayStation / Switch controllers the pad bridge shows to isolated games in a slot. */ + bridged: z.array(BridgedPadSchema).optional(), }) export const helperMethods = { @@ -51,6 +54,10 @@ export const helperMethods = { result: z.object({ windows: z.array(WindowInfoSchema) }), }, listControllers: { params: empty, result: ControllerListSchema }, + setPadBridge: { + params: z.object({ enabled: z.boolean() }), + result: z.object({ enabled: z.boolean() }), + }, listDisplays: { params: empty, result: z.object({ displays: z.array(DisplaySchema) }) }, findProcesses: { params: z.object({ names: z.array(z.string()) }), diff --git a/src/main/native/simulated-backend.ts b/src/main/native/simulated-backend.ts index 523f0f9..5b06e0e 100644 --- a/src/main/native/simulated-backend.ts +++ b/src/main/native/simulated-backend.ts @@ -193,6 +193,8 @@ export class SimulatedBackend implements NativeBackend { controllers: this.controllers, hidGamepads: [{ vendorId: 0x054c, productId: 0x0ce6 }], } + case 'setPadBridge': + return { enabled: p['enabled'] === true } case 'listDisplays': return { displays: DISPLAYS } case 'findProcesses': diff --git a/src/main/services/device-service.ts b/src/main/services/device-service.ts index 869c8b7..eb41a8c 100644 --- a/src/main/services/device-service.ts +++ b/src/main/services/device-service.ts @@ -1,14 +1,25 @@ /** * Controllers and displays: cached lists kept fresh by helper events (no polling here). */ -import type { Controller, ControllerState, Display, HidGamepad, PollingRate } from '@shared/domain' +import type { + BridgedPad, + Controller, + ControllerState, + Display, + HidGamepad, + PollingRate, +} from '@shared/domain' import { resolveModels } from '@shared/gamepad-models' import { INPUT_TOOL_EXES, toolsFromProcesses } from '@shared/input-tools' import type { NativeBackend } from '../native/backend' import { Emitter } from '../util/emitter' -function withModels(list: { controllers: Controller[]; hidGamepads?: HidGamepad[] }): Controller[] { - return resolveModels(list.controllers, list.hidGamepads ?? []) +function withModels(list: { + controllers: Controller[] + hidGamepads?: HidGamepad[] + bridged?: BridgedPad[] +}): Controller[] { + return resolveModels(list.controllers, list.hidGamepads ?? [], list.bridged ?? []) } export class DeviceService { diff --git a/src/renderer/src/components/ControllerSlotCard.vue b/src/renderer/src/components/ControllerSlotCard.vue index fc17faf..2dcdf68 100644 --- a/src/renderer/src/components/ControllerSlotCard.vue +++ b/src/renderer/src/components/ControllerSlotCard.vue @@ -63,6 +63,9 @@ defineEmits<{ select: [] }>() {{ controller.wireless ? $t('controllers.wireless') : $t('controllers.wired') }} + {{ + $t('controllers.bridge.badge') + }} {{ $t('controllers.doubled') }} diff --git a/src/renderer/src/i18n/de.ts b/src/renderer/src/i18n/de.ts index 1218dd7..37f9d43 100644 --- a/src/renderer/src/i18n/de.ts +++ b/src/renderer/src/i18n/de.ts @@ -338,6 +338,11 @@ export const de: Messages = { wired: 'Kabel', use: 'Für Spiel nutzen', inUse: 'Ausgewählt', + bridge: { + title: 'PlayStation- und Switch-Controller als Xbox-Controller', + hint: 'DualShock 4, DualSense und Switch Pro erscheinen isolierten Spielen als Xbox-Controller auf einem freien Platz, ohne Treiber. Vibration funktioniert über USB. Schalte es für Spiele ein, die diese Controller nicht erkennen; ein Spiel, das sie bereits unterstützt, kann doppelt reagieren.', + badge: 'Über InputSplit', + }, rate: { measure: 'Abfragerate messen', measuring: 'Bewege einen Stick 2 Sekunden lang im Kreis…', diff --git a/src/renderer/src/i18n/en.ts b/src/renderer/src/i18n/en.ts index 968b7f3..cb33555 100644 --- a/src/renderer/src/i18n/en.ts +++ b/src/renderer/src/i18n/en.ts @@ -333,6 +333,11 @@ export const en = { wired: 'Wired', use: 'Use for game', inUse: 'Selected', + bridge: { + title: 'PlayStation and Switch controllers as an Xbox controller', + hint: 'DualShock 4, DualSense and Switch Pro controllers appear to isolated games as an Xbox controller in a free slot, without drivers. Vibration works over USB. Turn it on for games that do not see these controllers; a game that already supports them may react twice.', + badge: 'Via InputSplit', + }, rate: { measure: 'Measure polling rate', measuring: 'Move a stick in circles for 2 seconds…', diff --git a/src/renderer/src/i18n/es.ts b/src/renderer/src/i18n/es.ts index 5b3c85f..5549b7a 100644 --- a/src/renderer/src/i18n/es.ts +++ b/src/renderer/src/i18n/es.ts @@ -337,6 +337,11 @@ export const es: Messages = { wired: 'Con cable', use: 'Usar en el juego', inUse: 'Elegido', + bridge: { + title: 'Mandos de PlayStation y Switch como mando de Xbox', + hint: 'DualShock 4, DualSense y Switch Pro aparecen en los juegos aislados como un mando de Xbox en una ranura libre, sin controladores. La vibración funciona por USB. Actívalo para juegos que no ven estos mandos; un juego que ya los admite puede reaccionar dos veces.', + badge: 'Vía InputSplit', + }, rate: { measure: 'Medir la frecuencia de sondeo', measuring: 'Mueve un stick en círculos durante 2 segundos…', diff --git a/src/renderer/src/i18n/fr.ts b/src/renderer/src/i18n/fr.ts index 813a8bb..3592b64 100644 --- a/src/renderer/src/i18n/fr.ts +++ b/src/renderer/src/i18n/fr.ts @@ -337,6 +337,11 @@ export const fr: Messages = { wired: 'Filaire', use: 'Utiliser pour le jeu', inUse: 'Choisie', + bridge: { + title: 'Manettes PlayStation et Switch comme manette Xbox', + hint: 'Les DualShock 4, DualSense et Switch Pro apparaissent aux jeux isolés comme une manette Xbox sur un emplacement libre, sans pilote. La vibration fonctionne en USB. Activez-le pour les jeux qui ne voient pas ces manettes ; un jeu qui les prend déjà en charge peut réagir deux fois.', + badge: 'Via InputSplit', + }, rate: { measure: 'Mesurer la fréquence d’interrogation', measuring: 'Faites tourner un stick pendant 2 secondes…', diff --git a/src/renderer/src/i18n/ja.ts b/src/renderer/src/i18n/ja.ts index 239d75c..96bc598 100644 --- a/src/renderer/src/i18n/ja.ts +++ b/src/renderer/src/i18n/ja.ts @@ -341,6 +341,11 @@ export const ja: Messages = { wired: '有線', use: 'ゲームで使う', inUse: '選択済み', + bridge: { + title: 'PlayStation と Switch のコントローラーを Xbox コントローラーとして使う', + hint: 'DualShock 4、DualSense、Switch Pro が、分離中のゲームには空きスロットの Xbox コントローラーとして見えます。ドライバーは不要です。振動は USB 接続で動作します。これらのコントローラーを認識しないゲームで有効にしてください。すでに対応しているゲームでは二重に反応することがあります。', + badge: 'InputSplit 経由', + }, rate: { measure: 'ポーリングレートを測定', measuring: 'スティックを 2 秒間回してください…', diff --git a/src/renderer/src/i18n/pl.ts b/src/renderer/src/i18n/pl.ts index de3cb82..b0160b6 100644 --- a/src/renderer/src/i18n/pl.ts +++ b/src/renderer/src/i18n/pl.ts @@ -331,6 +331,11 @@ export const pl: Messages = { wired: 'Przewodowy', use: 'Użyj w grze', inUse: 'Wybrany', + bridge: { + title: 'Kontrolery PlayStation i Switch jako kontroler Xbox', + hint: 'DualShock 4, DualSense i Switch Pro są widoczne dla izolowanych gier jako kontroler Xbox w wolnym gnieździe, bez sterowników. Wibracje działają przez USB. Włącz dla gier, które nie widzą tych kontrolerów; gra, która już je obsługuje, może reagować podwójnie.', + badge: 'Przez InputSplit', + }, rate: { measure: 'Zmierz częstotliwość odpytywania', measuring: 'Kręć gałką przez 2 sekundy…', diff --git a/src/renderer/src/i18n/pt-BR.ts b/src/renderer/src/i18n/pt-BR.ts index 84f7cee..52321bb 100644 --- a/src/renderer/src/i18n/pt-BR.ts +++ b/src/renderer/src/i18n/pt-BR.ts @@ -333,6 +333,11 @@ export const ptBR: Messages = { wired: 'Com fio', use: 'Usar no jogo', inUse: 'Escolhido', + bridge: { + title: 'Controles de PlayStation e Switch como controle Xbox', + hint: 'DualShock 4, DualSense e Switch Pro aparecem nos jogos isolados como um controle Xbox num slot livre, sem drivers. A vibração funciona por USB. Ative para jogos que não veem esses controles; um jogo que já os suporta pode reagir duas vezes.', + badge: 'Via InputSplit', + }, rate: { measure: 'Medir a taxa de atualização', measuring: 'Gire um analógico por 2 segundos…', diff --git a/src/renderer/src/i18n/ru.ts b/src/renderer/src/i18n/ru.ts index 36ed7e4..1773f35 100644 --- a/src/renderer/src/i18n/ru.ts +++ b/src/renderer/src/i18n/ru.ts @@ -328,6 +328,11 @@ export const ru: Messages = { wired: 'Проводной', use: 'Для игры', inUse: 'Выбран', + bridge: { + title: 'Геймпады PlayStation и Switch как Xbox-геймпад', + hint: 'DualShock 4, DualSense и Switch Pro видны изолированным играм как Xbox-геймпад в свободном слоте, без драйверов. Вибрация работает по USB. Включайте для игр, которые эти геймпады не видят; игра, которая их уже поддерживает, может реагировать дважды.', + badge: 'Через InputSplit', + }, rate: { measure: 'Измерить частоту опроса', measuring: 'Покрутите стик 2 секунды…', diff --git a/src/renderer/src/i18n/tr.ts b/src/renderer/src/i18n/tr.ts index 5b12b58..0af786f 100644 --- a/src/renderer/src/i18n/tr.ts +++ b/src/renderer/src/i18n/tr.ts @@ -329,6 +329,11 @@ export const tr: Messages = { wired: 'Kablolu', use: 'Oyun için kullan', inUse: 'Seçildi', + bridge: { + title: 'PlayStation ve Switch kumandaları Xbox kumandası olarak', + hint: 'DualShock 4, DualSense ve Switch Pro, yalıtılmış oyunlara boş bir yuvada Xbox kumandası olarak görünür, sürücü gerekmez. Titreşim USB ile çalışır. Bu kumandaları görmeyen oyunlar için açın; onları zaten destekleyen bir oyun iki kez tepki verebilir.', + badge: 'InputSplit üzerinden', + }, rate: { measure: 'Yoklama hızını ölç', measuring: 'Bir çubuğu 2 saniye daire çizerek çevirin…', diff --git a/src/renderer/src/i18n/uk.ts b/src/renderer/src/i18n/uk.ts index b536489..b664d33 100644 --- a/src/renderer/src/i18n/uk.ts +++ b/src/renderer/src/i18n/uk.ts @@ -328,6 +328,11 @@ export const uk: Messages = { wired: 'Дротовий', use: 'Для гри', inUse: 'Вибрано', + bridge: { + title: 'Геймпади PlayStation і Switch як Xbox-геймпад', + hint: 'DualShock 4, DualSense і Switch Pro видно ізольованим іграм як Xbox-геймпад у вільному слоті, без драйверів. Вібрація працює через USB. Вмикайте для ігор, які цих геймпадів не бачать; гра, що вже їх підтримує, може реагувати двічі.', + badge: 'Через InputSplit', + }, rate: { measure: 'Виміряти частоту опитування', measuring: 'Покрутіть стік 2 секунди…', diff --git a/src/renderer/src/i18n/zh-CN.ts b/src/renderer/src/i18n/zh-CN.ts index 238aa69..0aaee1b 100644 --- a/src/renderer/src/i18n/zh-CN.ts +++ b/src/renderer/src/i18n/zh-CN.ts @@ -314,6 +314,11 @@ export const zhCN: Messages = { wired: '有线', use: '用于游戏', inUse: '已选择', + bridge: { + title: '将 PlayStation 和 Switch 手柄作为 Xbox 手柄', + hint: 'DualShock 4、DualSense 和 Switch Pro 会以空闲插槽中的 Xbox 手柄出现在隔离的游戏中,无需驱动。通过 USB 连接时支持震动。请为识别不到这些手柄的游戏开启;已支持它们的游戏可能会触发两次。', + badge: '通过 InputSplit', + }, rate: { measure: '测量轮询率', measuring: '转动摇杆 2 秒…', diff --git a/src/renderer/src/views/ControllersView.vue b/src/renderer/src/views/ControllersView.vue index 0969653..78211cb 100644 --- a/src/renderer/src/views/ControllersView.vue +++ b/src/renderer/src/views/ControllersView.vue @@ -14,11 +14,14 @@ import UiCallout from '../components/ui/UiCallout.vue' import UiCard from '../components/ui/UiCard.vue' import UiEmptyState from '../components/ui/UiEmptyState.vue' import UiSelect from '../components/ui/UiSelect.vue' +import UiSwitch from '../components/ui/UiSwitch.vue' +import { useSettingsStore } from '../stores/settings' import { useBackendStore } from '../stores/backend' import { useDevicesStore } from '../stores/devices' import { useIsolationStore } from '../stores/isolation' const devices = useDevicesStore() +const settings = useSettingsStore() const isolation = useIsolationStore() const backend = useBackendStore() @@ -170,6 +173,24 @@ onBeforeUnmount(() => void devices.stopTest().catch(() => {}))

{{ $t('controllers.glyphsTip') }}

+ + + + @@ -121,6 +123,12 @@ export const HidGamepadSchema = z.object({ }) export type HidGamepad = z.infer +export const BridgedPadSchema = z.object({ + slot: z.number().int().min(0).max(3), + vendorId: z.number().int(), + productId: z.number().int(), +}) +export type BridgedPad = z.infer /** Controller test: how often the controller sent new data (null: it disconnected). */ export const PollingRateSchema = z.object({ slot: z.number().int().min(0).max(3), @@ -456,6 +464,8 @@ const ADDED_SETTINGS_FIELDS = { blockGameBarButton: z.boolean(), /** Tell the player on the TV when their controller disconnects or its battery runs low. */ controllerAlerts: z.boolean(), + /** Show PlayStation and Switch controllers to isolated games as Xbox controllers. */ + padBridge: z.boolean(), } export const SettingsSchema = z.object({ @@ -479,6 +489,7 @@ export const SettingsSchema = z.object({ }), blockGameBarButton: ADDED_SETTINGS_FIELDS.blockGameBarButton.default(true), controllerAlerts: ADDED_SETTINGS_FIELDS.controllerAlerts.default(true), + padBridge: ADDED_SETTINGS_FIELDS.padBridge.default(false), }) export type Settings = z.infer @@ -597,6 +608,7 @@ export const BACKUP_SETTINGS_KEYS = [ 'gamepadTuning', 'blockGameBarButton', 'controllerAlerts', + 'padBridge', 'showAllWindows', 'verboseLogging', 'theme', diff --git a/src/shared/gamepad-models.test.ts b/src/shared/gamepad-models.test.ts index 0747b1b..8e9f538 100644 --- a/src/shared/gamepad-models.test.ts +++ b/src/shared/gamepad-models.test.ts @@ -57,3 +57,17 @@ describe('resolveModels', () => { expect(result.map((c) => c.model)).toEqual([undefined, undefined]) }) }) + +describe('resolveModels with the pad bridge', () => { + it('shows a bridged pad in its slot and keeps it out of translator matching', () => { + const empty = { ...pad(1, null, null), connected: false } + const result = resolveModels( + [pad(0, 0x28de, 0x11ff), empty], + [{ vendorId: 0x054c, productId: 0x0ce6 }], + [{ slot: 1, vendorId: 0x054c, productId: 0x0ce6 }], + ) + expect(result[1]).toMatchObject({ connected: true, model: 'dualsense', bridged: true }) + expect(result[0]!.model).toBe('generic') + expect(result[0]!.doubled).toBeUndefined() + }) +}) diff --git a/src/shared/gamepad-models.ts b/src/shared/gamepad-models.ts index 66aa498..eeff7ff 100644 --- a/src/shared/gamepad-models.ts +++ b/src/shared/gamepad-models.ts @@ -6,7 +6,13 @@ * which shows up as a virtual Xbox controller; for those slots the helper also lists the * physical HID game controllers that are not XInput devices, and they are matched in order. */ -import { GamepadModelSchema, type Controller, type GamepadModel, type HidGamepad } from './domain' +import { + GamepadModelSchema, + type BridgedPad, + type Controller, + type GamepadModel, + type HidGamepad, +} from './domain' export const GAMEPAD_MODELS = GamepadModelSchema.options export type { GamepadModel } @@ -40,12 +46,38 @@ function maybeVirtual(c: Controller): boolean { } /** Adds `model` to every connected gamepad slot. */ -export function resolveModels(controllers: Controller[], hidGamepads: HidGamepad[]): Controller[] { - // Physical pads XInput cannot see directly: the ones a translator stands in for. - const hidden = hidGamepads +export function resolveModels( + controllers: Controller[], + hidGamepads: HidGamepad[], + bridged: BridgedPad[] = [], +): Controller[] { + // Physical pads XInput cannot see directly: the ones a translator stands in for. Pads + // InputSplit's own bridge holds are shown in their slot instead. + const unbridged = [...hidGamepads] + for (const pad of bridged) { + const i = unbridged.findIndex( + (h) => h.vendorId === pad.vendorId && h.productId === pad.productId, + ) + if (i !== -1) unbridged.splice(i, 1) + } + const hidden = unbridged .map((pad) => modelFromIds(pad.vendorId, pad.productId)) .filter((model): model is GamepadModel => model !== null && model !== 'xbox') return controllers.map((c) => { + const bridge = bridged.find((pad) => pad.slot === c.slot) + if (!c.connected && bridge !== undefined) { + return { + ...c, + connected: true, + kind: 'gamepad', + wireless: null, + battery: null, + vendorId: bridge.vendorId, + productId: bridge.productId, + model: modelFromIds(bridge.vendorId, bridge.productId) ?? 'generic', + bridged: true, + } + } if (!c.connected || c.kind !== 'gamepad') return { ...c, model: undefined } if (maybeVirtual(c) && hidden.length > 0) return { ...c, model: hidden.shift(), doubled: true } const fromIds =