PC 上游戏控制器 I/O 的代码和全面解释
This guide aims to provide everything you need to know about implementing joystick input in PC games. Prerequisites: familiarity with Windows programming and C-style C++.
TLDR: if you're a solo indie developer who just wants good basic joystick support, use SDL Game Controller. It's a well designed library that offloads tons of headaches.
The src folder contains small example programs to illustrate implementation details. You can build the Windows examples in Visual Studio by opening Joystick Input Examples.sln in the vs folder, or by running the build batch files with a Visual Studio developer command line. The combined.cpp example uses RawInput and XInput to demonstrate a more complete Windows implementation. You can build the Linux examples by running make.
Special thanks to Handmade Network for fostering a community that values exploring details, as well as Martins for sharing his limitless knowledge.
Standing for Human Interface Device, HID is a standardized communication protocol for USB devices a user directly interacts with, covering anything from keyboards to treadmills. An HID usage page is a number describing the purpose of the device, and usages are further subcategories. Modern game controllers use HID usage page 1 (generic desktop) with usage 0x04 (Joystick) or 0x05 (Gamepad), and Windows has several APIs for working with them. You can read the official usage table from usb.org, or this more concise reference.
HID refers to the standard protocol, physical devices (the gamepad in your hands), and virtual devices. Games interface with the virtual device while a driver handles communicating those bytes to the physical one. I'll be redundantly referring to game controllers as HID devices.
The only controllers you're likely to find that don't use HID are Microsoft's own XBox controllers. These use custom communication protocols and Microsoft introduced a new API to work with them. XBox 360 controllers use XUSB protocol and XBox One controllers use Game Input Protocol (GIP). There's a driver for each: xboxgip.sys and xusb22.sys. We'll refer to the driver and the API as XInput. It supports up to 4 controllers at a time, with a light on the controller indicating the player index.
The XInput API is one of the simplest APIs Microsoft has ever made and is extremely easy to use, but it only works with XBox controllers. This is nice for indie developers as XBox controllers are a small, consistent subset of the wide world of USB game controllers, and doing XBox support well is significantly easier than supporting all possible controllers. The downside is alienating players who only have a PS4 controller, or some other controller that uses HID.
XBox controllers also work on older games that only implemented support for HID. The XInput driver creates a virtual HID device and forwards inputs to it. Effectively there are two copies of each XBox controller on your system, the XInput version and the HID version. The HID version comes with a downside: the XInput driver combines both shoulder tiggers into one axis when converted to HID. Pressing RT makes the axis go in the negative direction, and LT makes it go in the positive direction. If you press both at the same time, it's the same as pressing neither. Windows Registry values can change this behavior to separate the triggers, though a game would require administrative privileges to automatically set them.
The basic inputs on joysticks are
Just like how HID devices are described by a usage page and usage, each input on an HID device is also described by a usage page and usage. The standard usages for values are X, Y, Z, Rx, Ry, Rz, Dial, Slider (usages 0x30-0x37 on usage page 1), and Hat Switch (0x39). The only consistant ones are X and Y for the left analog stick, and Hat Switch for Dpad; the rest are arbitrary and their names don't have much practical meaning these days. Buttons are on usage page 9 with each button getting its own usage, starting at 0x01. Subtract 1 from the usage and you'll have the corresponding button index in most APIs.
Analog sticks are sensitive and produce small input values even when at rest. Deadzones are used to ignore the input until it passes a threshold; for example, if(axis-0.2) axis=0. Deadzones can be applied to individual axes, or both analog stick axes together for better results.
Joysticks may support non-standard inputs such as touchpads and accelerometers. For HID devices, these are delivered along with standardized data, but are specific to the device and must be reverse-engineered. See Specialized I/O for how to access device-specific data.
Outputs are usually non-standard extensions, such as
Specialty devices like flightsticks support HID force feedback, but not the controllers currently popular for games; XBox and PS4 controllers can't do rumble through HID. XInput provides a function to cause rumble on XBox controllers. You can set rumble and LED color on PS4 controllers by directly writing reverse-engineered data through RawInput.
Some APIs have "Effects" for force feedback that get generalized and complex, but XBox and PS4 rumble is activated through two simple linear values—one for each motor in the gamepad. If a program never turns off rumble, XBox controllers will stop rumbling when the program terminates. PS4 controllers will continue to rumble on Windows, but stop after a few seconds of receiving no instructions.
On Windows 10, you can use the Windows Runtime API to get correct input from both XInput and HID devices. To support older versions of Windows, you will need to use the XInput API to get input from XBox controllers with correct shoulder trigger values, along with one of the HID APIs to get input from other types of controllers. When enumerating connected HID devices, you can check which ones are XBox controllers and ignore them with the HID API, then use XInput to process them. There's unfortunately no way to associate a virtual HID device with an XInput player index.
Multimedia Joystick is the simplest HID API for Windows. The Ex version of the functions and structs support up to 16 controllers at a time, each with up to 32 buttons, 6 axes, and a hat.
Getting the joystick state is one function call to joyGetPosEx, which takes a device index and a struct to fill with data. The device index ranges 0-15, and a joystick can be assigned any index, even if it's the only one connected at the time. You'll have to check all of the indices to find which are in use.
Multimedia's functionality is quite limited. It doesn't have any force feedback support, and is missing two axes (Dial and Slider) that are used by some controllers. It also doesn't give you handles to hardware, so you can't easily tell what's an Xbox controller to use XInput instead.
The JOYCAPS struct does contain vendor ID (wMid) and Product ID (wPid). These could be compared against a list of known XBox controller IDs. In addition, they can be used to look up the joystick's name in the registry. See this example in Vojtěch Boček's libenjoy.
DirectInput is lower level and gives a bit more control. It uses a COM interface, so you'll be creating an object that's used to create other objects. First create a DirectInput object with DirectInput8Create(). You can use IDirectInput* or IDirectInput8*; the 8 versions give access to full features, though those features are not used in the directinput.cpp example.
To find available joysticks you'll have to enumerate them through a callback function. DirectInput will invoke this function once for each joystick plugged into your machine.
MSDN provides a function to check if a device is an XBox controller while enumerating HID devices. It searches through all devices on the system to see if they have "IG_" in the device name. If it does, it compares the product and vendor IDs to the direct input device passed into the function, and, if they match, returns that the device is an XBox controller.
One you've accuired devices, you can call GetDeviceState on them to fill a DIJOYSTATE struct with the current state of inputs on the controller. The value members of the struct have names corresponding to their HID usages, except for Dial, which is combined with Slider in an array of two elements.
Device Caps, short for capabilities, contains information about what features the device has, such as number of buttons.
DirectInput has an "Effects" interface for HID force feedback. Good for flightsticks, but there's no support for XBox or Playstation controller rumble.
The first step with RawInput is registering to receive WM_INPUT events. Unlike the other APIs, RawInput uses an event queue to get inputs. This has a distinct advantage of being able to get inputs that may have been missed between frames, such as a button being quickly pressed and released (though most games don't worry about this; it would have to be running well under 30fps for players to notice). To register for events, fill out one or more RAWINPUTDEVICE structs and pass an array of them to RegisterRawInputDevices(). The structs take the HID usage page and usages of devices for which to receive events, bit flags, and a handle to the window whose window procedure will receive the events. You can use your game window's existing procedure, or create a non-visible window to enc
暂无开放 Issues,或尚未同步最近议题。