diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 58a5d8d306..fce12b8f1b 100755 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -181,6 +181,8 @@ jobs: target: esp32 - path: 'components/ft5x06/example' target: esp32s3 + - path: 'components/gamepad_map/example' + target: esp32s3 - path: 'components/gfps_service/example' target: esp32s3 - path: 'components/gps/example' diff --git a/.github/workflows/gamepad_map_tests.yml b/.github/workflows/gamepad_map_tests.yml new file mode 100644 index 0000000000..ac7219ea44 --- /dev/null +++ b/.github/workflows/gamepad_map_tests.yml @@ -0,0 +1,75 @@ +name: Gamepad map host test + +# Builds and runs, on the host with g++ -std=c++23: +# - components/gamepad_map/test/gamepad_map_host_test.cpp (GamepadState, +# GamepadMap rules + validation, the hid-rp conversion, GamepadProfiles' +# file round trip) +# - components/hid-rp/test/hid_rp_report_map_host_test.cpp (the runtime +# report map + Gamepad / Keyboard / Mouse decoders the map is fed from) +# Runs whenever either component, or what they store / log with, changes. + +# Minimal token scope: build + run tests, never writes. +permissions: + contents: read + +on: + pull_request: + paths: + - "components/gamepad_map/**" + - "components/hid-rp/**" + - "components/persistent_data/**" + - "components/serialization/**" + - "components/logger/**" + - "components/format/**" + - "components/base_component/**" + - ".github/workflows/gamepad_map_tests.yml" + push: + branches: + - main + paths: + - "components/gamepad_map/**" + - "components/hid-rp/**" + - "components/persistent_data/**" + - "components/serialization/**" + - "components/logger/**" + - "components/format/**" + - "components/base_component/**" + - ".github/workflows/gamepad_map_tests.yml" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + host-test: + name: C++ host tests (gamepad map, hid-rp report map) + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + - name: Build and run hid_rp_report_map_host_test + run: | + g++ --version | head -1 + g++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \ + -isystem components/hid-rp/include \ + -isystem components/hid-rp/detail/hid-rp/hid-rp \ + -isystem components/format/include \ + -isystem components/format/detail/fmt/include \ + components/hid-rp/test/hid_rp_report_map_host_test.cpp -o hid_rp_report_map_host_test + ./hid_rp_report_map_host_test + - name: Build and run gamepad_map_host_test + run: | + g++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \ + -I components/gamepad_map/include -I components/persistent_data/include \ + -I components/serialization/include -I components/base_component/include \ + -I components/logger/include -I components/format/include \ + -isystem components/serialization/detail/alpaca/include \ + -isystem components/format/detail/fmt/include \ + -isystem components/hid-rp/include \ + -isystem components/hid-rp/detail/hid-rp/hid-rp \ + components/gamepad_map/test/gamepad_map_host_test.cpp components/logger/src/logger.cpp \ + -o gamepad_map_host_test + ./gamepad_map_host_test diff --git a/.github/workflows/upload_components.yml b/.github/workflows/upload_components.yml index d845826d2b..510bfd4969 100755 --- a/.github/workflows/upload_components.yml +++ b/.github/workflows/upload_components.yml @@ -119,6 +119,7 @@ jobs: components/format components/ft5x06 components/ftp + components/gamepad_map components/gfps_service components/gps components/gt911 diff --git a/components/gamepad_map/CMakeLists.txt b/components/gamepad_map/CMakeLists.txt new file mode 100644 index 0000000000..eddea4ac62 --- /dev/null +++ b/components/gamepad_map/CMakeLists.txt @@ -0,0 +1,4 @@ +idf_component_register( + INCLUDE_DIRS "include" + REQUIRES base_component format hid-rp persistent_data + ) diff --git a/components/gamepad_map/README.md b/components/gamepad_map/README.md new file mode 100644 index 0000000000..ae028bb0eb --- /dev/null +++ b/components/gamepad_map/README.md @@ -0,0 +1,136 @@ +# Gamepad Map Component + +[![Badge](https://components.espressif.com/components/espp/gamepad_map/badge.svg)](https://components.espressif.com/components/espp/gamepad_map) + +The `gamepad_map` component remaps a gamepad's buttons and axes: button to +button, analog to digital, digital to analog and analog to analog, plus stick +dead zones. Maps are stored per controller type in a file with +[persistent_data](../persistent_data). The component is meant to sit between +whatever reads a controller (a BLE or USB HID gamepad, GPIO buttons) and +whatever comes next (an emulated USB controller, an emulator's input). + + +**Table of Contents** + +- [Gamepad Map Component](#gamepad-map-component) + - [Overview](#overview) + - [Gamepad state](#gamepad-state) + - [Rules](#rules) + - [Profiles](#profiles) + - [From a HID gamepad](#from-a-hid-gamepad) + - [Host test](#host-test) + - [Example](#example) + + + +## Overview + +| Type | What it is | +|------|------------| +| `espp::GamepadState` | Buttons by position plus six axes: the common format inputs are decoded into | +| `espp::GamepadMapRule` | One remap: where one control's input goes | +| `espp::GamepadMap` | Stick dead zones plus a list of rules; `apply()` maps one state to another | +| `espp::GamepadProfiles` | A default map plus one map per controller type, saved in a file | +| `espp::to_gamepad_state()` | A state from a `hid_rp::GamepadReport` (`gamepad_state_hid_rp.hpp`) | + +Everything except `GamepadProfiles` is header-only plain data with no +allocation in `apply()`, so it can run on every report. + +## Gamepad state + +`espp::GamepadState` names face buttons by **position** (south / east / west / +north), not label, because the labels disagree between controller families: + +| Position | Xbox | Nintendo | PlayStation | +|----------|------|----------|-------------| +| south | A | B | Cross | +| east | B | A | Circle | +| west | X | Y | Square | +| north | Y | X | Triangle | + +Besides the face buttons there are L1/R1, L2/R2 (the triggers as buttons), +L3/R3, Select, Start, Home, Capture, the d-pad and four paddles. The axes are +the two sticks (-32767..32767, X right, Y **down**, as in HID) and the two +triggers (0..32767). + +## Rules + +| Kind | Effect | `param` | +|------|--------|---------| +| button → button | the source presses the target | - | +| axis → button | the target is pressed while the axis is past the threshold | threshold: positive = at or above, negative = at or below | +| button → axis | while pressed, the value is added to the target axis | value | +| axis → axis | the scaled source is added to the target axis | scale in percent, -400..400 (negative inverts) | + +A control that is the source of a rule is **moved**: it no longer reaches its +own position unless the rule has `KEEP_SOURCE`. A rule with target `NONE` +removes its source. Several rules can feed one target: buttons are OR-ed and +axis contributions are summed, then clamped to the axis' range. Every control +that no rule takes as a source passes through unchanged, so an empty map is the +identity. + +```cpp +espp::GamepadMap map; +map.swap(B::South, B::East) // Nintendo-style A / B + .left_stick_to_dpad() // the stick also drives the d-pad + .triggers_to_buttons() // analog triggers also press ZL / ZR + .add(espp::GamepadMapRule::button(B::Paddle1, B::South)); // a paddle as A +map.left_deadzone_percent = 8; + +espp::GamepadState out = map.apply(in); +``` + +Check a map that came from outside (a file, a web page) with `valid()`. +`apply()` skips rules whose indices are out of range, so a bad map can never +read or write outside the state. + +## Profiles + +`espp::GamepadProfiles` keeps a default map and one `GamepadProfile` per +controller type, keyed by vendor and product ID. For BLE these come from the +Device Information service's PnP ID; for USB, from the device descriptor. A +controller that reports neither is matched by name. Every change is validated +and saved atomically. Look the map up when a controller connects, not on every +report: + +```cpp +espp::GamepadProfiles profiles({.file_path = fs.get_root_path() / "gamepad_profiles.bin", + .default_map = legacy_settings_as_a_map}); +espp::GamepadMap active = profiles.map_for(vid, pid, name); +``` + +The file is written on the first change. Until then the configured +`default_map` is used, which is how an application can migrate its older +settings into a map. + +## From a HID gamepad + +The runtime `hid_rp::GamepadDecoder` (`hid-rp-report-map.hpp`) decodes any HID +gamepad from its report descriptor. For a pass-through, turn off its emulator +conveniences (stick as d-pad, triggers as L2/R2, Capture as Home) so the map +decides those: + +```cpp +auto report_map = espp::hid_rp::ReportMap::parse(descriptor); +if (!report_map || !espp::hid_rp::GamepadDecoder::looks_like_gamepad(*report_map)) + return; // not a gamepad (or a malformed descriptor) +espp::hid_rp::GamepadDecoder decoder(std::move(*report_map)); +decoder.set_combine_controls(false); + +espp::hid_rp::GamepadReport report; +if (decoder.update(report_id, payload, report)) // BLE: the ID comes out of band + send(map.apply(espp::to_gamepad_state(report))); +``` + +## Host test + +`test/gamepad_map_host_test.cpp` covers the rule semantics, validation, the +hid-rp conversion (with a real BLE gamepad's descriptor) and the profile store's +file round trip. The build command is at the top of the file, and CI runs it in +`.github/workflows/gamepad_map_tests.yml` together with the hid-rp report-map +test. + +## Example + +The [example](./example) decodes a BLE gamepad report, remaps it, and stores +per-controller profiles on a LittleFS partition. diff --git a/components/gamepad_map/example/CMakeLists.txt b/components/gamepad_map/example/CMakeLists.txt new file mode 100644 index 0000000000..096a698bcb --- /dev/null +++ b/components/gamepad_map/example/CMakeLists.txt @@ -0,0 +1,22 @@ +# The following lines of boilerplate have to be in your project's CMakeLists +# in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.20) + +set(ENV{IDF_COMPONENT_MANAGER} "0") +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +# add the component directories that we want to use +set(EXTRA_COMPONENT_DIRS + "../../../components/" +) + +set( + COMPONENTS + "main esptool_py logger file_system gamepad_map" + CACHE STRING + "List of components to include" + ) + +project(gamepad_map_example) + +set(CMAKE_CXX_STANDARD 23) diff --git a/components/gamepad_map/example/README.md b/components/gamepad_map/example/README.md new file mode 100644 index 0000000000..71d24d6a59 --- /dev/null +++ b/components/gamepad_map/example/README.md @@ -0,0 +1,61 @@ +# Gamepad Map Example + +This example shows the `gamepad_map` component between a gamepad and whatever +comes next: + +1. A BLE gamepad's HID report map (a ShanWan BSP-D8 in its Android mode) is + parsed with `hid_rp::ReportMap` and decoded with `hid_rp::GamepadDecoder`, + with the decoder's emulator conveniences turned off. +2. Each decoded report becomes an `espp::GamepadState`, which an + `espp::GamepadMap` remaps. The map here swaps A/B to the Nintendo layout, + puts the left stick on the d-pad as well, makes the analog triggers press + ZL/ZR too, and adds a left-stick dead zone. +3. `espp::GamepadProfiles` stores a default map and a per-controller-type + profile in a file on a [littlefs](https://github.com/littlefs-project/littlefs) + partition, and reloads them. + +It ends with a pass / fail summary. + +## How to use example + +### Hardware Required + +Any ESP32 with a `littlefs` partition (see `partitions.csv`). The partition +label is configured through `menuconfig` +(`CONFIG_ESPP_FILE_SYSTEM_PARTITION_LABEL`). + +### Build and Flash + +Build the project and flash it to the board, then run the monitor tool to view +serial output: + +``` +idf.py -p PORT flash monitor +``` + +(Replace PORT with the name of the serial port to use.) + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the Getting Started Guide for full steps to configure and use ESP-IDF to build projects. + +## Expected Output + +``` +I (…) gamepad map example: Starting gamepad map example! +I (…) gamepad map example: Decode a BLE gamepad report, then remap it +I (…) gamepad map example: controller: {buttons: [south], lx: -32767, ly: 128, rx: 128, ry: 128, lt: 0, rt: 32767} +I (…) gamepad map example: mapped: {buttons: [east, r2, left], lx: -32767, ly: 128, rx: 128, ry: 128, lt: 0, rt: 32767} + [PASS] south is mapped to east + [PASS] the left stick also presses d-pad left + [PASS] the stick is kept + [PASS] the right trigger also presses R2 +I (…) gamepad map example: Per-controller profiles in a file +I (…) gamepad map example: BSP-D8 map: 4 rule(s); default map: 2 rule(s) + [PASS] the profile is used for its controller + [PASS] other controllers get the default map + [PASS] profiles survive a reload + [PASS] erase a profile +I (…) gamepad map example: 8 passed, 0 failed +I (…) gamepad map example: Gamepad map example complete! +``` diff --git a/components/gamepad_map/example/main/CMakeLists.txt b/components/gamepad_map/example/main/CMakeLists.txt new file mode 100644 index 0000000000..a941e22ba7 --- /dev/null +++ b/components/gamepad_map/example/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRC_DIRS "." + INCLUDE_DIRS ".") diff --git a/components/gamepad_map/example/main/gamepad_map_example.cpp b/components/gamepad_map/example/main/gamepad_map_example.cpp new file mode 100644 index 0000000000..42c8f39471 --- /dev/null +++ b/components/gamepad_map/example/main/gamepad_map_example.cpp @@ -0,0 +1,130 @@ +#include +#include +#include +#include + +#include "file_system.hpp" +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state_formatters.hpp" +#include "gamepad_state_hid_rp.hpp" +#include "logger.hpp" + +using namespace std::chrono_literals; + +// The HID report map of a BLE gamepad (a ShanWan BSP-D8 in its Android mode), +// as read from its Report Map characteristic: report 3 = consumer keys, +// report 4 = 8-bit X/Y/Z/Rz sticks, a hat, 16 buttons, Brake / Accelerator. +static const char *kReportMapHex = + "050c0901a1018503751095011501269c0219012a9c028100c005010905a10185040901a1000930093109320935" + "150026ff00750895048102c00939150025073500463b016514750495018142750495018101050919012910150025" + "017501951081020502150026ff0009c409c5950275088102750895018101c0"; + +static std::vector from_hex(const char *hex) { + std::vector out; + for (; hex[0] && hex[1]; hex += 2) + out.push_back(static_cast(std::stoi(std::string(hex, 2), nullptr, 16))); + return out; +} + +extern "C" void app_main(void) { + espp::Logger logger({.tag = "gamepad map example", .level = espp::Logger::Verbosity::INFO}); + logger.info("Starting gamepad map example!"); + + int passed = 0; + int failed = 0; + auto check = [&](const char *name, bool ok) { + fmt::print(" [{}] {}\n", ok ? "PASS" : "FAIL", name); + (ok ? passed : failed)++; + }; + + using B = espp::GamepadState::Button; + using A = espp::GamepadState::Axis; + + { + logger.info("Decode a BLE gamepad report, then remap it"); + //! [gamepad map example] + // At connect: parse the controller's report map once and keep a decoder. + // A bridge decodes every control as only itself and lets the map decide. + auto report_map = espp::hid_rp::ReportMap::parse(from_hex(kReportMapHex)); + if (!report_map || !espp::hid_rp::GamepadDecoder::looks_like_gamepad(*report_map)) { + logger.error("Not a gamepad report map"); + return; + } + espp::hid_rp::GamepadDecoder decoder(std::move(*report_map)); + decoder.set_combine_controls(false); + + // The map: Nintendo-style A/B (south <-> east), the left stick also on the + // d-pad, analog triggers also as ZL / ZR, a 10% left-stick dead zone. + espp::GamepadMap map; + map.swap(B::South, B::East).left_stick_to_dpad().triggers_to_buttons(); + map.left_deadzone_percent = 10; + std::string why; + if (!map.valid(&why)) + logger.error("Invalid map: {}", why); + + // For every report: decode (BLE delivers the report ID out of band), map, + // and hand the result on. Here: the south button (A), left stick fully + // left, right trigger fully pressed. + const std::vector payload{0x00, 0x80, 0x80, 0x80, 0x0f, 0x01, 0x00, 0xff, 0x00, 0x00}; + espp::hid_rp::GamepadReport report; + if (decoder.update(4, payload, report)) { + const espp::GamepadState in = espp::to_gamepad_state(report); + const espp::GamepadState out = map.apply(in); + logger.info("controller: {}", in); + logger.info("mapped: {}", out); + } + //! [gamepad map example] + espp::hid_rp::GamepadReport r; + decoder.update(4, payload, r); + const auto out = map.apply(espp::to_gamepad_state(r)); + check("south is mapped to east", out.pressed(B::East) && !out.pressed(B::South)); + check("the left stick also presses d-pad left", out.pressed(B::Left)); + check("the stick is kept", out.axis(A::LeftX) < -30000); + check("the right trigger also presses R2", out.pressed(B::R2)); + } + + { + logger.info("Per-controller profiles in a file"); + auto &fs = espp::FileSystem::get(); + const std::filesystem::path path = fs.get_root_path() / "gamepad_profiles.bin"; + std::error_code ec; + std::filesystem::remove(path, ec); // start clean for the checks below + //! [gamepad profiles example] + // The default map is used for controllers without a profile; the file is + // written on the first change. + espp::GamepadMap default_map; + default_map.invert(A::LeftY).invert(A::RightY); // up-positive sticks for this host + espp::GamepadProfiles profiles({ + .file_path = path, + .default_map = default_map, + .log_level = espp::Logger::Verbosity::INFO, + }); + + // A profile for one controller type (vendor / product ID; from the BLE + // Device Information PnP ID, or the USB device descriptor). + espp::GamepadMap bsp_d8 = default_map; + bsp_d8.swap(B::South, B::East); + if (!profiles.set_profile({.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp_d8}, ec)) + logger.error("Could not save the profile: {}", ec.message()); + + // When a controller connects, look its map up once and keep it. + const espp::GamepadMap active = profiles.map_for(0x1949, 0x0402, "BSP-D8"); + logger.info("BSP-D8 map: {} rule(s); default map: {} rule(s)", active.rules.size(), + profiles.default_map().rules.size()); + //! [gamepad profiles example] + check("the profile is used for its controller", active == bsp_d8); + check("other controllers get the default map", profiles.map_for(0x045e, 0x0b13) == default_map); + espp::GamepadProfiles reloaded({.file_path = path}); + check("profiles survive a reload", + reloaded.map_for(0x1949, 0x0402) == bsp_d8 && reloaded.default_map() == default_map); + check("erase a profile", reloaded.erase_profile(0x1949, 0x0402, "", ec) && !ec && + reloaded.map_for(0x1949, 0x0402) == default_map); + } + + logger.info("{} passed, {} failed", passed, failed); + logger.info("Gamepad map example complete!"); + while (true) { + std::this_thread::sleep_for(1s); + } +} diff --git a/components/gamepad_map/example/partitions.csv b/components/gamepad_map/example/partitions.csv new file mode 100644 index 0000000000..4196003405 --- /dev/null +++ b/components/gamepad_map/example/partitions.csv @@ -0,0 +1,5 @@ +# Name, Type, SubType, Offset, Size +nvs, data, nvs, 0x9000, 0x6000 +phy_init, data, phy, 0xf000, 0x1000 +factory, app, factory, 0x10000, 2M +littlefs, data, littlefs, , 1M diff --git a/components/gamepad_map/example/sdkconfig.defaults b/components/gamepad_map/example/sdkconfig.defaults new file mode 100644 index 0000000000..169de32462 --- /dev/null +++ b/components/gamepad_map/example/sdkconfig.defaults @@ -0,0 +1,12 @@ +# Common ESP-related +# +CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=4096 +CONFIG_ESP_MAIN_TASK_STACK_SIZE=8192 + +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y + +# +# Partition Table +# +CONFIG_PARTITION_TABLE_CUSTOM=y +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" diff --git a/components/gamepad_map/idf_component.yml b/components/gamepad_map/idf_component.yml new file mode 100644 index 0000000000..20efd4f705 --- /dev/null +++ b/components/gamepad_map/idf_component.yml @@ -0,0 +1,24 @@ +## IDF Component Manager Manifest File +license: "MIT" +description: "Gamepad button / axis remapping with per-controller profiles for ESP-IDF" +url: "https://github.com/esp-cpp/espp/tree/main/components/gamepad_map" +repository: "git://github.com/esp-cpp/espp.git" +maintainers: + - William Emfinger +documentation: "https://esp-cpp.github.io/espp/input/gamepad_map.html" +examples: + - path: example +tags: + - cpp + - Component + - Input + - Gamepad + - HID +dependencies: + idf: + version: '>=5.0' + espp/base_component: '>=1.0' + espp/format: '>=1.0' + # GamepadReport::lt / rt / capture and GamepadDecoder::set_combine_controls() + espp/hid-rp: '>=1.4.6' + espp/persistent_data: '>=1.0' diff --git a/components/gamepad_map/include/gamepad_map.hpp b/components/gamepad_map/include/gamepad_map.hpp new file mode 100644 index 0000000000..d88f137a6d --- /dev/null +++ b/components/gamepad_map/include/gamepad_map.hpp @@ -0,0 +1,353 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include "gamepad_state.hpp" + +namespace espp { + +/** + * @brief One rule of a GamepadMap: where one control's input goes. + * + * @details Four kinds of rule cover the remaps controllers need: + * - **button -> button**: the source button presses the target + * (swap A/B, move a function to a paddle); + * - **axis -> button**: the target is pressed while the source axis + * is past a threshold (a stick direction as the d-pad, an analog + * trigger as ZL/ZR). A positive threshold presses at values >= it, + * a negative one at values <= it (stick up / left); + * - **button -> axis**: while the source button is pressed it adds a + * value to the target axis (the d-pad as the left stick, a button + * as a full trigger); + * - **axis -> axis**: the source axis, scaled by a percentage (a + * negative scale inverts), is added to the target (swap or invert + * sticks, a stick as a trigger). A trigger inverted onto a trigger + * reads from full: (32767 - value) x |scale|, so it rests pressed. + * + * A control that is the source of a rule no longer reaches its own + * position (it is "moved", not copied) unless the rule sets + * KEEP_SOURCE; a rule whose target is NONE just removes its source. + * Several rules may feed one target: buttons are OR-ed, axis + * contributions are summed and clamped. + * + * The rules of a map form a table applied to the controller's input + * all at once, not one after the other: every rule reads the input + * as the controller reported it, never another rule's output. So a + * control that is the source of two rules feeds both targets + * (`swap(South, East).swap(East, North)` makes East press South AND + * North), and `invert(LeftY).swap_sticks()` sends the left stick's Y + * inverted to itself and as is to the right stick. Give each source + * the one rule (or, with KEEP_SOURCE, the rules) it should have. + * + * The struct is plain data (it is stored with PersistentData and + * sent over the wire as is); build rules with the static helpers. + */ +struct GamepadMapRule { + using Button = GamepadState::Button; + using Axis = GamepadState::Axis; + + /// What the source and target are. + enum class Kind : uint8_t { + ButtonToButton, ///< param unused + AxisToButton, ///< param = threshold (sign = direction), never 0 + ButtonToAxis, ///< param = value added to the target while pressed + AxisToAxis, ///< param = scale in percent, -400..400 (negative inverts) + }; + + static constexpr uint8_t NONE = 0xFF; ///< target: remove the source, send it nowhere + static constexpr uint8_t KEEP_SOURCE = 0x01; ///< flag: the source also stays where it was + static constexpr int16_t MAX_SCALE_PERCENT = 400; + + Kind kind{Kind::ButtonToButton}; + uint8_t source{0}; ///< a Button or an Axis (by kind) + uint8_t target{NONE}; ///< a Button or an Axis (by kind), or NONE + uint8_t flags{0}; ///< KEEP_SOURCE + int16_t param{0}; ///< see Kind + + /// @brief Whether the source stays at its own position too. + constexpr bool keeps_source() const { return flags & KEEP_SOURCE; } + /// @brief Whether the source is an axis. + constexpr bool source_is_axis() const { + return kind == Kind::AxisToButton || kind == Kind::AxisToAxis; + } + /// @brief Whether the target is an axis. + constexpr bool target_is_axis() const { + return kind == Kind::ButtonToAxis || kind == Kind::AxisToAxis; + } + + /// @brief `from` presses `to`. + static constexpr GamepadMapRule button(Button from, Button to, bool keep_source = false) { + return {Kind::ButtonToButton, static_cast(from), static_cast(to), + keep_flag(keep_source), 0}; + } + /// @brief `to` is pressed while `from` is at or past `threshold` (a negative + /// threshold: at or below it). 16384 is half way. + static constexpr GamepadMapRule axis_to_button(Axis from, int16_t threshold, Button to, + bool keep_source = false) { + return {Kind::AxisToButton, static_cast(from), static_cast(to), + keep_flag(keep_source), threshold}; + } + /// @brief While `from` is pressed, `value` is added to `to` (e.g. 32767 for a + /// full trigger, -32767 for the left stick fully left). + static constexpr GamepadMapRule button_to_axis(Button from, Axis to, int16_t value, + bool keep_source = false) { + return {Kind::ButtonToAxis, static_cast(from), static_cast(to), + keep_flag(keep_source), value}; + } + /// @brief `from` scaled by `scale_percent` is added to `to` (-100 inverts). + static constexpr GamepadMapRule axis(Axis from, Axis to, int16_t scale_percent = 100, + bool keep_source = false) { + return {Kind::AxisToAxis, static_cast(from), static_cast(to), + keep_flag(keep_source), scale_percent}; + } + /// @brief Remove a button. + static constexpr GamepadMapRule disable(Button b) { + return {Kind::ButtonToButton, static_cast(b), NONE, 0, 0}; + } + /// @brief Remove an axis (it reads 0 / released). + static constexpr GamepadMapRule disable(Axis a) { + return {Kind::AxisToAxis, static_cast(a), NONE, 0, 100}; + } + + /// @brief Whether the rule is well formed; `why` (if given) says what is wrong. + bool valid(std::string *why = nullptr) const { + auto fail = [why](const char *reason) { + if (why) + *why = reason; + return false; + }; + if (kind > Kind::AxisToAxis) + return fail("unknown rule kind"); + if (flags & ~KEEP_SOURCE) + return fail("unknown flags"); + const size_t sources = source_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + const size_t targets = target_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + if (source >= sources) + return fail("source out of range"); + if (target != NONE && target >= targets) + return fail("target out of range"); + if (kind == Kind::AxisToButton && param == 0) + return fail("axis -> button needs a non-zero threshold"); + if (kind == Kind::AxisToAxis && (param < -MAX_SCALE_PERCENT || param > MAX_SCALE_PERCENT)) + return fail("axis -> axis scale out of range"); + return true; + } + + constexpr bool operator==(const GamepadMapRule &) const = default; + +private: + static constexpr uint8_t keep_flag(bool keep) { return keep ? KEEP_SOURCE : 0; } +}; + +/** + * @brief A button / axis mapping for a gamepad: radial stick dead zones plus a + * list of GamepadMapRule. + * + * @details apply() turns the state a controller reports into the state to + * send on: dead zones first (they belong to the physical sticks), + * then the rules; every control no rule takes as its source passes + * through unchanged, so an empty map is the identity. apply() does + * not allocate and touches each rule twice, so it is cheap enough to + * run on every report. + * + * A GamepadMap is plain data: copy it, store it (see GamepadProfiles), + * send it. Use valid() on one that came from outside (a file, a web + * page) before using it. + * + * \section gamepad_map_ex1 Gamepad Map Example + * \snippet gamepad_map_example.cpp gamepad map example + */ +struct GamepadMap { + using Button = GamepadState::Button; + using Axis = GamepadState::Axis; + using Rule = GamepadMapRule; + + static constexpr size_t MAX_RULES = 64; ///< rules a valid map may hold + static constexpr uint8_t MAX_DEADZONE_PERCENT = 90; ///< largest valid dead zone + + uint8_t left_deadzone_percent{0}; ///< radial dead zone of the left stick, 0..90 + uint8_t right_deadzone_percent{0}; ///< radial dead zone of the right stick, 0..90 + std::vector rules{}; + + /// @brief Whether the map is well formed; `why` (if given) says what is wrong. + bool valid(std::string *why = nullptr) const { + if (left_deadzone_percent > MAX_DEADZONE_PERCENT || + right_deadzone_percent > MAX_DEADZONE_PERCENT) { + if (why) + *why = "dead zone out of range"; + return false; + } + if (rules.size() > MAX_RULES) { + if (why) + *why = "too many rules"; + return false; + } + for (size_t i = 0; i < rules.size(); i++) { + std::string reason; + if (!rules[i].valid(&reason)) { + if (why) + *why = "rule " + std::to_string(i) + ": " + reason; + return false; + } + } + return true; + } + + /// @brief Whether the map changes nothing. + bool is_identity() const { + return left_deadzone_percent == 0 && right_deadzone_percent == 0 && rules.empty(); + } + + /// @brief Map `in` to `out` (they may be the same object). Rules that are + /// not valid() are skipped. + void apply(const GamepadState &in_state, GamepadState &out) const { + GamepadState in = in_state; // `out` may alias `in_state` + apply_deadzone(in, Axis::LeftX, Axis::LeftY, left_deadzone_percent); + apply_deadzone(in, Axis::RightX, Axis::RightY, right_deadzone_percent); + + // controls moved elsewhere do not pass through + uint32_t moved_buttons = 0; + uint32_t moved_axes = 0; + for (const auto &r : rules) { + if (r.keeps_source() || !usable(r)) + continue; + (r.source_is_axis() ? moved_axes : moved_buttons) |= 1u << r.source; + } + std::array sum{}; + for (size_t a = 0; a < GamepadState::AXIS_COUNT; a++) { + if (!(moved_axes & (1u << a))) + sum[a] = in.axes[a]; + } + uint32_t buttons = in.buttons & ~moved_buttons; + + for (const auto &r : rules) { + if (r.target == Rule::NONE || !usable(r)) + continue; + switch (r.kind) { + case Rule::Kind::ButtonToButton: + if ((in.buttons >> r.source) & 1u) + buttons |= 1u << r.target; + break; + case Rule::Kind::AxisToButton: { + const int16_t v = in.axes[r.source]; + if (r.param > 0 ? v >= r.param : v <= r.param) + buttons |= 1u << r.target; + break; + } + case Rule::Kind::ButtonToAxis: + if ((in.buttons >> r.source) & 1u) + sum[r.target] += r.param; + break; + case Rule::Kind::AxisToAxis: { + const int32_t v = in.axes[r.source]; + const bool trigger_to_trigger = GamepadState::is_trigger(static_cast(r.source)) && + GamepadState::is_trigger(static_cast(r.target)); + // an inverted trigger onto a trigger reads from full instead of + // going negative (which would clamp to "never pressed") + sum[r.target] += trigger_to_trigger && r.param < 0 + ? (GamepadState::AXIS_MAX - v) * -r.param / 100 + : v * r.param / 100; + break; + } + } + } + out.buttons = buttons; + for (size_t a = 0; a < GamepadState::AXIS_COUNT; a++) + out.axes[a] = GamepadState::clamp(static_cast(a), sum[a]); + } + + /// @brief The mapped copy of `in`. + GamepadState apply(const GamepadState &in) const { + GamepadState out; + apply(in, out); + return out; + } + + // --- building maps --- + + /// @brief Add a rule (no check: see valid()). Returns *this for chaining. + GamepadMap &add(const GamepadMapRule &rule) { + rules.push_back(rule); + return *this; + } + /// @brief Exchange two buttons (e.g. south/east for Nintendo A/B placement). + GamepadMap &swap(Button a, Button b) { return add(Rule::button(a, b)).add(Rule::button(b, a)); } + /// @brief Exchange two axes (e.g. the sticks, one axis at a time). + GamepadMap &swap(Axis a, Axis b) { return add(Rule::axis(a, b)).add(Rule::axis(b, a)); } + /// @brief Invert an axis (stick Y up-positive, say; a trigger then rests fully pressed). + GamepadMap &invert(Axis a) { return add(Rule::axis(a, a, -100)); } + /// @brief Exchange the left and right sticks. + GamepadMap &swap_sticks() { + return swap(Axis::LeftX, Axis::RightX).swap(Axis::LeftY, Axis::RightY); + } + /// @brief The left stick also drives the d-pad past `threshold` (default 50%). + GamepadMap &left_stick_to_dpad(int16_t threshold = 16384, bool keep_stick = true) { + return add(Rule::axis_to_button(Axis::LeftX, static_cast(-threshold), Button::Left, + keep_stick)) + .add(Rule::axis_to_button(Axis::LeftX, threshold, Button::Right, keep_stick)) + .add(Rule::axis_to_button(Axis::LeftY, static_cast(-threshold), Button::Up, + keep_stick)) + .add(Rule::axis_to_button(Axis::LeftY, threshold, Button::Down, keep_stick)); + } + /// @brief The d-pad also drives the left stick to full deflection. + GamepadMap &dpad_to_left_stick(bool keep_dpad = true) { + return add(Rule::button_to_axis(Button::Left, Axis::LeftX, -GamepadState::AXIS_MAX, keep_dpad)) + .add(Rule::button_to_axis(Button::Right, Axis::LeftX, GamepadState::AXIS_MAX, keep_dpad)) + .add(Rule::button_to_axis(Button::Up, Axis::LeftY, -GamepadState::AXIS_MAX, keep_dpad)) + .add(Rule::button_to_axis(Button::Down, Axis::LeftY, GamepadState::AXIS_MAX, keep_dpad)); + } + /// @brief The analog triggers also press L2 / R2 past `threshold` (default 40%). + GamepadMap &triggers_to_buttons(int16_t threshold = 13107, bool keep_triggers = true) { + return add(Rule::axis_to_button(Axis::LeftTrigger, threshold, Button::L2, keep_triggers)) + .add(Rule::axis_to_button(Axis::RightTrigger, threshold, Button::R2, keep_triggers)); + } + /// @brief L2 / R2 also pull the analog triggers fully (for digital-trigger pads). + GamepadMap &buttons_to_triggers(bool keep_buttons = true) { + return add(Rule::button_to_axis(Button::L2, Axis::LeftTrigger, GamepadState::AXIS_MAX, + keep_buttons)) + .add(Rule::button_to_axis(Button::R2, Axis::RightTrigger, GamepadState::AXIS_MAX, + keep_buttons)); + } + + bool operator==(const GamepadMap &) const = default; + +private: + static bool usable(const GamepadMapRule &r) { + // the cheap part of valid(): indices in range, so apply() never reads or + // writes outside the state + const size_t sources = + r.source_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + const size_t targets = + r.target_is_axis() ? GamepadState::AXIS_COUNT : GamepadState::BUTTON_COUNT; + return r.kind <= GamepadMapRule::Kind::AxisToAxis && r.source < sources && + (r.target == GamepadMapRule::NONE || r.target < targets) && + !(r.kind == GamepadMapRule::Kind::AxisToButton && r.param == 0); + } + + static void apply_deadzone(GamepadState &s, Axis x_axis, Axis y_axis, uint8_t percent) { + if (percent == 0 || percent > MAX_DEADZONE_PERCENT) + return; + const float x = s.axis(x_axis), y = s.axis(y_axis); + const float mag = std::sqrt(x * x + y * y); + const float dead = GamepadState::AXIS_MAX * (percent / 100.0f); + if (mag <= dead) { + s.set(x_axis, 0); + s.set(y_axis, 0); + return; + } + // rescale what is left so the edge of the dead zone reads 0 and full + // deflection still reads full; the magnitude is not capped (each axis is + // clamped on its own), so a square-gate corner stays a full diagonal + const float scale = + ((mag - dead) / (GamepadState::AXIS_MAX - dead)) * GamepadState::AXIS_MAX / mag; + s.set(x_axis, static_cast(std::lround(x * scale))); + s.set(y_axis, static_cast(std::lround(y * scale))); + } +}; + +} // namespace espp diff --git a/components/gamepad_map/include/gamepad_profiles.hpp b/components/gamepad_map/include/gamepad_profiles.hpp new file mode 100644 index 0000000000..0ae9fa777a --- /dev/null +++ b/components/gamepad_map/include/gamepad_profiles.hpp @@ -0,0 +1,349 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "base_component.hpp" +#include "gamepad_map.hpp" +#include "persistent_data.hpp" + +namespace espp { + +/** + * @brief The map for one type of controller. + * + * @details A controller type is its USB / Bluetooth vendor and product ID + * (for BLE, from the Device Information service's PnP ID). A + * controller that reports neither (VID and PID 0) is matched by its + * name instead. + */ +struct GamepadProfile { + /// Longest name stored; longer names are cut to it (and compared cut). + static constexpr size_t MAX_NAME_LENGTH = 64; + + uint16_t vid{0}; ///< vendor ID (0 = unknown: match by name) + uint16_t pid{0}; ///< product ID (0 = unknown: match by name) + std::string name{}; ///< for display, and the key when VID and PID are 0 + GamepadMap map{}; ///< the mapping for this controller type + + /// @brief A name as stored (cut to MAX_NAME_LENGTH bytes). + static std::string clip_name(const std::string &n) { return n.substr(0, MAX_NAME_LENGTH); } + + /// @brief Whether this profile is for the controller with these IDs / name. + bool matches(uint16_t vid_, uint16_t pid_, const std::string &name_) const { + if (vid == 0 && pid == 0) + return vid_ == 0 && pid_ == 0 && !name.empty() && clip_name(name) == clip_name(name_); + return vid == vid_ && pid == pid_; + } + /// @brief Whether any controller can match this profile. + bool matchable() const { return vid != 0 || pid != 0 || !name.empty(); } + + bool operator==(const GamepadProfile &) const = default; +}; + +/// @brief The data a GamepadProfiles store keeps (schema version 1). +struct GamepadProfilesV1 { + static constexpr uint32_t VERSION = 1; + GamepadMap default_map{}; ///< for a controller without a profile + std::vector profiles{}; ///< per controller type +}; + +/** + * @brief Per-controller-type gamepad maps, stored in a file with + * PersistentData. + * + * @details Holds a default map plus one GamepadProfile per controller type, + * and saves every change atomically (see PersistentData) to a file on + * a mounted filesystem (LittleFS, SPIFFS, SD). Look a controller up + * when it connects (map_for()) and keep the returned map for its + * reports; the lookup copies the map and is not meant for every + * report. + * + * Every map that comes in is checked with GamepadMap::valid(). From a + * file, an invalid rule is dropped (the rest of its map kept), and a + * profile no controller can match, a duplicate or one over the limit + * is dropped, each with a warning. A file that cannot be read (corrupt, + * or written by a newer firmware) is renamed to `.unreadable` + * and the store starts from the defaults, so the next change does not + * overwrite what may still be recoverable (see load_error()). + * + * Thread-safe. + * + * \section gamepad_profiles_ex1 Gamepad Profiles Example + * \snippet gamepad_map_example.cpp gamepad profiles example + */ +class GamepadProfiles : public BaseComponent { +public: + using Data = GamepadProfilesV1; + using Storage = PersistentData; + + /** + * @brief Configuration for the GamepadProfiles. + */ + struct Config { + std::filesystem::path file_path; ///< file the profiles live in + GamepadMap default_map{}; ///< default map when the file does not exist yet + size_t max_profiles{16}; ///< profiles the store accepts + Logger::Verbosity log_level{Logger::Verbosity::WARN}; ///< Verbosity of the logger + }; + + /** + * @brief Load the profiles (or start from `config.default_map` when there is + * no file yet; the file is written on the first change). + * @param config The configuration. + */ + explicit GamepadProfiles(const Config &config) + : BaseComponent("GamepadProfiles", config.log_level) + , max_profiles_(config.max_profiles) + , storage_({.file_path = config.file_path, + .auto_load = false, + .max_file_size = max_file_size(config.max_profiles), + .log_level = config.log_level}) { + std::error_code ec; + if (storage_.load(ec)) { + data_ = sanitize(storage_.get()); + } else { + if (ec != make_error_code(PersistentDataErrc::file_not_found)) { + load_error_ = ec; + keep_unreadable(config.file_path, ec); + } + data_.default_map = config.default_map.valid() ? config.default_map : GamepadMap{}; + } + // only data_ is used from here on: do not keep a second copy in storage_ + storage_.set(Data{}); + } + + /// @brief Why the file could not be loaded (it was set aside as + /// `.unreadable`); clear if it loaded or did not exist. + std::error_code load_error() const { return load_error_; } + + /// @brief The map for a controller: its profile's, else the default map. + GamepadMap map_for(uint16_t vid, uint16_t pid, const std::string &name = {}) const { + std::lock_guard lock(mutex_); + const auto *p = find(vid, pid, name); + return p ? p->map : data_.default_map; + } + + /// @brief The profile for a controller, if it has one. + std::optional profile(uint16_t vid, uint16_t pid, + const std::string &name = {}) const { + std::lock_guard lock(mutex_); + const auto *p = find(vid, pid, name); + return p ? std::optional(*p) : std::nullopt; + } + + /// @brief Whether a controller has a profile of its own. + bool has_profile(uint16_t vid, uint16_t pid, const std::string &name = {}) const { + std::lock_guard lock(mutex_); + return find(vid, pid, name) != nullptr; + } + + /// @brief Every profile. + std::vector profiles() const { + std::lock_guard lock(mutex_); + return data_.profiles; + } + + /// @brief How many profiles are stored. + size_t profile_count() const { + std::lock_guard lock(mutex_); + return data_.profiles.size(); + } + + /// @brief The map for controllers without a profile. + GamepadMap default_map() const { + std::lock_guard lock(mutex_); + return data_.default_map; + } + + /// @brief Everything, as stored. + Data data() const { + std::lock_guard lock(mutex_); + return data_; + } + + /// @brief The most profiles the store accepts. + size_t max_profiles() const { return max_profiles_; } + + /** + * @brief Replace the default map and save. + * @param map The map (must be valid()). + * @param ec Set on failure: std::errc::invalid_argument for an invalid map, + * else the save error. + * @return true if saved. + */ + bool set_default_map(const GamepadMap &map, std::error_code &ec) { + if (!check(map, ec)) + return false; + std::lock_guard lock(mutex_); + Data next = data_; + next.default_map = map; + return commit(std::move(next), ec); + } + + /** + * @brief Add a profile, or replace the one for the same controller, and save. + * @param entry The profile (its map must be valid(); with VID and PID 0 it + * needs a name; a name is stored cut to MAX_NAME_LENGTH). + * @param ec Set on failure: std::errc::invalid_argument for an invalid + * profile, std::errc::no_buffer_space when the store is full, else + * the save error. + * @return true if saved. + */ + bool set_profile(const GamepadProfile &entry, std::error_code &ec) { + if (!check(entry.map, ec)) + return false; + if (entry.vid == 0 && entry.pid == 0 && entry.name.empty()) { + ec = std::make_error_code(std::errc::invalid_argument); + return false; + } + GamepadProfile stored = entry; + stored.name = GamepadProfile::clip_name(entry.name); + std::lock_guard lock(mutex_); + Data next = data_; + auto it = + std::find_if(next.profiles.begin(), next.profiles.end(), [&](const GamepadProfile &p) { + return p.matches(stored.vid, stored.pid, stored.name); + }); + if (it != next.profiles.end()) { + *it = std::move(stored); + } else if (next.profiles.size() >= max_profiles_) { + ec = std::make_error_code(std::errc::no_buffer_space); + return false; + } else { + next.profiles.push_back(std::move(stored)); + } + return commit(std::move(next), ec); + } + + /** + * @brief Remove a controller's profile (it then uses the default map) and save. + * @return true if saved; false with `ec` clear if there was no such profile. + */ + bool erase_profile(uint16_t vid, uint16_t pid, const std::string &name, std::error_code &ec) { + ec.clear(); + std::lock_guard lock(mutex_); + Data next = data_; + const auto before = next.profiles.size(); + std::erase_if(next.profiles, + [&](const GamepadProfile &p) { return p.matches(vid, pid, name); }); + if (next.profiles.size() == before) + return false; + return commit(std::move(next), ec); + } + + /** + * @brief Forget every profile and reset the default map to identity, and save. + * @return true if saved. + */ + bool reset(std::error_code &ec) { + std::lock_guard lock(mutex_); + return commit(Data{}, ec); + } + +private: + // An upper bound on the encoded size of a full store (every map at + // MAX_RULES, every name at MAX_NAME_LENGTH, with generous per-field + // overhead), so whatever save() writes, load() accepts. + static size_t max_file_size(size_t max_profiles) { + constexpr size_t map_bytes = 32 + GamepadMap::MAX_RULES * 16; + constexpr size_t profile_bytes = map_bytes + GamepadProfile::MAX_NAME_LENGTH + 32; + return std::max(64 * 1024, 1024 + map_bytes + max_profiles * profile_bytes); + } + + void keep_unreadable(const std::filesystem::path &file, const std::error_code &why) { + std::filesystem::path aside = file; + aside += ".unreadable"; + std::error_code ec; + std::filesystem::remove(aside, ec); + std::filesystem::rename(file, aside, ec); + if (ec) + logger_.error("Could not load {} ({}) nor set it aside ({}): the next change overwrites it", + file.string(), why.message(), ec.message()); + else + logger_.warn("Could not load {} ({}); kept it as {} and started from the defaults", + file.string(), why.message(), aside.string()); + } + + const GamepadProfile *find(uint16_t vid, uint16_t pid, const std::string &name) const { + auto it = std::find_if(data_.profiles.begin(), data_.profiles.end(), + [&](const GamepadProfile &p) { return p.matches(vid, pid, name); }); + return it == data_.profiles.end() ? nullptr : &*it; + } + + static bool check(const GamepadMap &map, std::error_code &ec) { + ec.clear(); + if (!map.valid()) { + ec = std::make_error_code(std::errc::invalid_argument); + return false; + } + return true; + } + + // save first, then take it: memory never holds what the file does not + bool commit(Data next, std::error_code &ec) { + ec.clear(); + const bool saved = storage_.save(next, ec); + storage_.set(Data{}); // the file has it; data_ is the one copy in memory + if (!saved) + return false; + data_ = std::move(next); + return true; + } + + // Keep what can be kept of a map from the file: its valid rules. + GamepadMap sanitize_map(GamepadMap m, const char *what) const { + if (m.left_deadzone_percent > GamepadMap::MAX_DEADZONE_PERCENT || + m.right_deadzone_percent > GamepadMap::MAX_DEADZONE_PERCENT) { + logger_.warn("{}: dead zone out of range; clamped", what); + m.left_deadzone_percent = std::min(m.left_deadzone_percent, GamepadMap::MAX_DEADZONE_PERCENT); + m.right_deadzone_percent = + std::min(m.right_deadzone_percent, GamepadMap::MAX_DEADZONE_PERCENT); + } + const size_t before = m.rules.size(); + std::erase_if(m.rules, [](const GamepadMapRule &r) { return !r.valid(); }); + if (m.rules.size() > GamepadMap::MAX_RULES) + m.rules.resize(GamepadMap::MAX_RULES); + if (m.rules.size() != before) + logger_.warn("{}: dropped {} invalid rule(s)", what, before - m.rules.size()); + return m; + } + + Data sanitize(Data d) const { + d.default_map = sanitize_map(std::move(d.default_map), "stored default map"); + std::vector kept; + for (auto &p : d.profiles) { + p.name = GamepadProfile::clip_name(p.name); + if (!p.matchable()) { + logger_.warn("Dropping a stored profile with no VID, PID or name"); + continue; + } + const bool dup = std::any_of(kept.begin(), kept.end(), [&](const GamepadProfile &k) { + return k.matches(p.vid, p.pid, p.name); + }); + if (dup || kept.size() >= max_profiles_) { + logger_.warn("Dropping the stored profile for {:04x}:{:04x} '{}': {}", p.vid, p.pid, p.name, + dup ? "duplicate" : "over the profile limit"); + continue; + } + p.map = sanitize_map(std::move(p.map), "a stored profile"); + kept.push_back(std::move(p)); + } + d.profiles = std::move(kept); + return d; + } + + size_t max_profiles_; + Storage storage_; + mutable std::mutex mutex_; + Data data_{}; + std::error_code load_error_{}; +}; + +} // namespace espp diff --git a/components/gamepad_map/include/gamepad_state.hpp b/components/gamepad_map/include/gamepad_state.hpp new file mode 100644 index 0000000000..2f42268e8d --- /dev/null +++ b/components/gamepad_map/include/gamepad_state.hpp @@ -0,0 +1,125 @@ +#pragma once + +#include +#include +#include + +namespace espp { + +/** + * @brief The state of a gamepad, by control position. + * + * @details The common currency of the gamepad_map component: inputs are + * decoded into it (from a HID report, a USB/BLE controller, GPIO + * buttons...), a GamepadMap rewrites it, and the result is encoded + * into whatever comes next (a USB controller report, an emulator's + * input). + * + * Face buttons are named by **position**, not label, because the + * labels disagree between controller families: south is Xbox A / + * Nintendo B / PlayStation Cross, east is Xbox B / Nintendo A / + * PlayStation Circle, west is Xbox X / Nintendo Y / Square and north + * is Xbox Y / Nintendo X / Triangle. + * + * Sticks are -32767..32767 with X growing to the right and Y growing + * **downwards** (the HID convention); triggers are 0..32767. + */ +struct GamepadState { + /// A digital control. + enum class Button : uint8_t { + South, ///< Xbox A, Nintendo B, PlayStation Cross + East, ///< Xbox B, Nintendo A, PlayStation Circle + West, ///< Xbox X, Nintendo Y, PlayStation Square + North, ///< Xbox Y, Nintendo X, PlayStation Triangle + L1, ///< left bumper / L + R1, ///< right bumper / R + L2, ///< left trigger as a button / ZL + R2, ///< right trigger as a button / ZR + L3, ///< left stick click + R3, ///< right stick click + Select, ///< View / Back / Minus / Share + Start, ///< Menu / Plus / Options + Home, ///< Guide / Home / PS + Capture, ///< Share (Xbox Series) / Capture (Nintendo) + Up, ///< d-pad up + Down, ///< d-pad down + Left, ///< d-pad left + Right, ///< d-pad right + Paddle1, ///< extra / back buttons (paddles, SL/SR...) + Paddle2, + Paddle3, + Paddle4, + Count ///< number of buttons (not a button) + }; + + /// An analog control. + enum class Axis : uint8_t { + LeftX, ///< left stick X, -32767 (left) .. 32767 (right) + LeftY, ///< left stick Y, -32767 (up) .. 32767 (down) + RightX, ///< right stick X + RightY, ///< right stick Y + LeftTrigger, ///< 0 (released) .. 32767 (fully pressed) + RightTrigger, ///< 0 (released) .. 32767 (fully pressed) + Count ///< number of axes (not an axis) + }; + + static constexpr size_t BUTTON_COUNT = static_cast(Button::Count); + static constexpr size_t AXIS_COUNT = static_cast(Axis::Count); + static constexpr int16_t AXIS_MAX = 32767; ///< full deflection of a stick or trigger + + uint32_t buttons{0}; ///< bit n = Button n pressed + std::array axes{}; ///< indexed by Axis + + /// @brief Whether a button is pressed. + constexpr bool pressed(Button b) const { + return b < Button::Count && (buttons >> static_cast(b)) & 1u; + } + /// @brief Press or release a button. + constexpr void set(Button b, bool down) { + if (b >= Button::Count) + return; + const uint32_t bit = 1u << static_cast(b); + buttons = down ? (buttons | bit) : (buttons & ~bit); + } + /// @brief The value of an axis (0 for an invalid axis). + constexpr int16_t axis(Axis a) const { + return a < Axis::Count ? axes[static_cast(a)] : 0; + } + /// @brief Set an axis, clamped to its range (see is_trigger()). + constexpr void set(Axis a, int32_t value) { + if (a >= Axis::Count) + return; + axes[static_cast(a)] = clamp(a, value); + } + + /// @brief Whether an axis is a trigger (0..32767) rather than a stick axis. + static constexpr bool is_trigger(Axis a) { + return a == Axis::LeftTrigger || a == Axis::RightTrigger; + } + /// @brief Clamp a value to an axis' range. + static constexpr int16_t clamp(Axis a, int32_t value) { + const int32_t lo = is_trigger(a) ? 0 : -AXIS_MAX; + return static_cast(value < lo ? lo : value > AXIS_MAX ? AXIS_MAX : value); + } + + /// @brief Short, stable name of a button ("south", "l1", "up"...), for logs and UIs. + static constexpr const char *name(Button b) { + constexpr const char *names[] = {"south", "east", "west", "north", "l1", "r1", + "l2", "r2", "l3", "r3", "select", "start", + "home", "capture", "up", "down", "left", "right", + "paddle1", "paddle2", "paddle3", "paddle4"}; + static_assert(sizeof(names) / sizeof(names[0]) == BUTTON_COUNT); + return b < Button::Count ? names[static_cast(b)] : "?"; + } + /// @brief Short, stable name of an axis ("left_x", "right_trigger"...). + static constexpr const char *name(Axis a) { + constexpr const char *names[] = {"left_x", "left_y", "right_x", + "right_y", "left_trigger", "right_trigger"}; + static_assert(sizeof(names) / sizeof(names[0]) == AXIS_COUNT); + return a < Axis::Count ? names[static_cast(a)] : "?"; + } + + bool operator==(const GamepadState &) const = default; +}; + +} // namespace espp diff --git a/components/gamepad_map/include/gamepad_state_formatters.hpp b/components/gamepad_map/include/gamepad_state_formatters.hpp new file mode 100644 index 0000000000..0851386fc7 --- /dev/null +++ b/components/gamepad_map/include/gamepad_state_formatters.hpp @@ -0,0 +1,26 @@ +#pragma once + +#include "format.hpp" +#include "gamepad_state.hpp" + +/// Formats a GamepadState as the pressed buttons by name plus the axes, e.g. +/// `{buttons: [south, up], lx: 0, ly: -32767, rx: 0, ry: 0, lt: 0, rt: 32767}`. +template <> struct fmt::formatter : fmt::formatter { + template + auto format(const espp::GamepadState &s, FormatContext &ctx) const -> decltype(ctx.out()) { + using B = espp::GamepadState::Button; + using A = espp::GamepadState::Axis; + auto out = fmt::format_to(ctx.out(), "{{buttons: ["); + bool first = true; + for (size_t i = 0; i < espp::GamepadState::BUTTON_COUNT; i++) { + const auto b = static_cast(i); + if (!s.pressed(b)) + continue; + out = fmt::format_to(out, "{}{}", first ? "" : ", ", espp::GamepadState::name(b)); + first = false; + } + return fmt::format_to(out, "], lx: {}, ly: {}, rx: {}, ry: {}, lt: {}, rt: {}}}", + s.axis(A::LeftX), s.axis(A::LeftY), s.axis(A::RightX), s.axis(A::RightY), + s.axis(A::LeftTrigger), s.axis(A::RightTrigger)); + } +}; diff --git a/components/gamepad_map/include/gamepad_state_hid_rp.hpp b/components/gamepad_map/include/gamepad_state_hid_rp.hpp new file mode 100644 index 0000000000..1433829698 --- /dev/null +++ b/components/gamepad_map/include/gamepad_state_hid_rp.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include "gamepad_state.hpp" +#include "hid-rp-report-map.hpp" + +namespace espp { + +/** + * @brief A GamepadState from a decoded HID gamepad report + * (hid_rp::GamepadDecoder). + * + * @details Both name buttons by position and share the stick convention + * (-32767..32767, Y down), so this is a field-by-field copy. For a + * pass-through (a controller bridge, a remapper) decode with + * `GamepadDecoder::set_combine_controls(false)`, so the d-pad, L2/R2 + * and Home are only what the controller reports for them and the map + * decides the rest. + * @param r The decoded report. + * @return The state. + */ +inline GamepadState to_gamepad_state(const hid_rp::GamepadReport &r) { + using B = GamepadState::Button; + using A = GamepadState::Axis; + GamepadState s; + s.set(B::South, r.south); + s.set(B::East, r.east); + s.set(B::West, r.west); + s.set(B::North, r.north); + s.set(B::L1, r.l1); + s.set(B::R1, r.r1); + s.set(B::L2, r.l2); + s.set(B::R2, r.r2); + s.set(B::L3, r.l3); + s.set(B::R3, r.r3); + s.set(B::Select, r.select); + s.set(B::Start, r.start); + s.set(B::Home, r.home); + s.set(B::Capture, r.capture); + s.set(B::Up, r.up); + s.set(B::Down, r.down); + s.set(B::Left, r.left); + s.set(B::Right, r.right); + s.set(A::LeftX, r.lx); + s.set(A::LeftY, r.ly); + s.set(A::RightX, r.rx); + s.set(A::RightY, r.ry); + s.set(A::LeftTrigger, r.lt); + s.set(A::RightTrigger, r.rt); + return s; +} + +} // namespace espp diff --git a/components/gamepad_map/test/gamepad_map_host_test.cpp b/components/gamepad_map/test/gamepad_map_host_test.cpp new file mode 100644 index 0000000000..2af77a1a1c --- /dev/null +++ b/components/gamepad_map/test/gamepad_map_host_test.cpp @@ -0,0 +1,375 @@ +// Host-buildable unit tests for the gamepad_map component (GamepadState, +// GamepadMap, the hid-rp conversion and GamepadProfiles). Build & run from the +// repository root (third-party headers are -isystem so their own warnings do +// not fail the build): +// +// g++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \ +// -I components/gamepad_map/include -I components/persistent_data/include \ +// -I components/serialization/include -I components/base_component/include \ +// -I components/logger/include -I components/format/include \ +// -isystem components/serialization/detail/alpaca/include \ +// -isystem components/format/detail/fmt/include \ +// -isystem components/hid-rp/include -isystem components/hid-rp/detail/hid-rp/hid-rp \ +// components/gamepad_map/test/gamepad_map_host_test.cpp components/logger/src/logger.cpp \ +// -o gamepad_map_host_test +// ./gamepad_map_host_test +// +// No ESP-IDF headers required. + +#include +#include +#include +#include +#include +#include + +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state_formatters.hpp" +#include "gamepad_state_hid_rp.hpp" + +static int failures = 0; +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); \ + failures++; \ + } \ + } while (0) + +using espp::GamepadMap; +using espp::GamepadMapRule; +using espp::GamepadState; +using B = GamepadState::Button; +using A = GamepadState::Axis; + +static GamepadState state(std::initializer_list pressed, + const std::array &axes = {}) { + GamepadState s; + for (auto b : pressed) + s.set(b, true); + s.axes = axes; + return s; +} + +static void test_state() { + GamepadState s; + s.set(B::East, true); + s.set(B::Paddle4, true); + CHECK(s.pressed(B::East) && s.pressed(B::Paddle4) && !s.pressed(B::South)); + s.set(B::East, false); + CHECK(!s.pressed(B::East)); + s.set(B::Count, true); // ignored + CHECK(s.buttons == (1u << static_cast(B::Paddle4))); + s.set(A::LeftX, -40000); + CHECK(s.axis(A::LeftX) == -32767); + s.set(A::RightTrigger, -5); + CHECK(s.axis(A::RightTrigger) == 0); // triggers do not go negative + CHECK(std::string(GamepadState::name(B::South)) == "south"); + CHECK(std::string(GamepadState::name(A::RightTrigger)) == "right_trigger"); + GamepadState f; + f.set(B::South, true); + f.set(B::Up, true); + f.set(A::LeftY, -32767); + f.set(A::RightTrigger, 32767); + CHECK(fmt::format("{}", f) == + "{buttons: [south, up], lx: 0, ly: -32767, rx: 0, ry: 0, lt: 0, rt: 32767}"); +} + +static void test_identity() { + GamepadMap map; + CHECK(map.is_identity() && map.valid()); + const auto in = state({B::South, B::Up, B::Home}, {100, -200, 300, -400, 500, 600}); + CHECK(map.apply(in) == in); +} + +static void test_swap_and_disable() { + GamepadMap map; + map.swap(B::South, B::East).add(GamepadMapRule::disable(B::Capture)); + CHECK(map.valid()); + auto out = map.apply(state({B::South, B::Capture, B::Start})); + CHECK(out.pressed(B::East) && !out.pressed(B::South)); + CHECK(!out.pressed(B::Capture)); + CHECK(out.pressed(B::Start)); // untouched controls pass through + out = map.apply(state({B::East})); + CHECK(out.pressed(B::South) && !out.pressed(B::East)); + out = map.apply(state({B::South, B::East})); + CHECK(out.pressed(B::South) && out.pressed(B::East)); +} + +static void test_keep_source_and_or() { + GamepadMap map; + // a paddle presses south too, keeping itself; L1 also presses south (moved) + map.add(GamepadMapRule::button(B::Paddle1, B::South, true)) + .add(GamepadMapRule::button(B::L1, B::South)); + auto out = map.apply(state({B::Paddle1})); + CHECK(out.pressed(B::Paddle1) && out.pressed(B::South)); + out = map.apply(state({B::L1})); + CHECK(out.pressed(B::South) && !out.pressed(B::L1)); + out = map.apply(state({B::South})); + CHECK(out.pressed(B::South)); // south is a target, not a source: still passes +} + +static void test_axis_to_button() { + GamepadMap map; + map.left_stick_to_dpad(16384, /*keep_stick=*/false).triggers_to_buttons(13107, true); + CHECK(map.valid()); + auto out = map.apply(state({}, {-20000, 20000, 0, 0, 13107, 13106})); + CHECK(out.pressed(B::Left) && !out.pressed(B::Right)); + CHECK(out.pressed(B::Down) && !out.pressed(B::Up)); + CHECK(out.axis(A::LeftX) == 0 && out.axis(A::LeftY) == 0); // the stick was moved + CHECK(out.pressed(B::L2) && !out.pressed(B::R2)); // >= threshold presses + CHECK(out.axis(A::LeftTrigger) == 13107); // kept + out = map.apply(state({}, {16383, -16384, 0, 0, 0, 0})); + CHECK(!out.pressed(B::Right) && out.pressed(B::Up)); +} + +static void test_button_to_axis() { + GamepadMap map; + map.dpad_to_left_stick(/*keep_dpad=*/false).buttons_to_triggers(true); + auto out = map.apply(state({B::Left, B::Down, B::R2}, {1000, 0, 0, 0, 0, 0})); + // the d-pad adds to the stick, which still passes through, then clamps + CHECK(out.axis(A::LeftX) == -32767 + 1000); + CHECK(out.axis(A::LeftY) == 32767); + CHECK(!out.pressed(B::Left) && !out.pressed(B::Down)); + CHECK(out.axis(A::RightTrigger) == 32767 && out.pressed(B::R2)); + out = map.apply(state({B::Left, B::Right})); + CHECK(out.axis(A::LeftX) == 0); // opposite directions cancel +} + +static void test_axis_to_axis() { + GamepadMap map; + map.invert(A::LeftY).swap_sticks(); + // invert(LeftY) moves LeftY to itself inverted; swap_sticks then moves LeftY + // to RightY as well: both contribute to their targets + auto out = map.apply(state({}, {100, 200, 300, 400, 0, 0})); + CHECK(out.axis(A::LeftX) == 300 && out.axis(A::RightX) == 100); + CHECK(out.axis(A::RightY) == 200); + CHECK(out.axis(A::LeftY) == 400 - 200); + + GamepadMap trig; + trig.add(GamepadMapRule::axis(A::RightY, A::RightTrigger, -100)); // stick up = trigger + out = trig.apply(state({}, {0, 0, 0, -32767, 0, 0})); + CHECK(out.axis(A::RightTrigger) == 32767 && out.axis(A::RightY) == 0); + out = trig.apply(state({}, {0, 0, 0, 32767, 0, 0})); + CHECK(out.axis(A::RightTrigger) == 0); // clamped at released + + // an inverted trigger reads from full instead of never moving + GamepadMap inv_trigger; + inv_trigger.invert(A::LeftTrigger); + CHECK(inv_trigger.apply(state({}, {0, 0, 0, 0, 0, 0})).axis(A::LeftTrigger) == 32767); + CHECK(inv_trigger.apply(state({}, {0, 0, 0, 0, 32767, 0})).axis(A::LeftTrigger) == 0); + CHECK(inv_trigger.apply(state({}, {0, 0, 0, 0, 1000, 0})).axis(A::LeftTrigger) == 31767); + // ... while a trigger inverted onto a stick goes negative + GamepadMap trig_to_stick; + trig_to_stick.add(GamepadMapRule::axis(A::RightTrigger, A::LeftY, -100)); + CHECK(trig_to_stick.apply(state({}, {0, 0, 0, 0, 0, 32767})).axis(A::LeftY) == -32767); + + GamepadMap gone; + gone.add(GamepadMapRule::disable(A::LeftTrigger)); + CHECK(gone.apply(state({}, {0, 0, 0, 0, 9000, 9000})).axis(A::LeftTrigger) == 0); +} + +static void test_deadzone() { + GamepadMap map; + map.left_deadzone_percent = 10; + auto out = map.apply(state({}, {3000, -1000, 3000, 0, 0, 0})); + CHECK(out.axis(A::LeftX) == 0 && out.axis(A::LeftY) == 0); + CHECK(out.axis(A::RightX) == 3000); // only the left stick + out = map.apply(state({}, {32767, 0, 0, 0, 0, 0})); + CHECK(out.axis(A::LeftX) == 32767); // full deflection still full + out = map.apply(state({}, {-20000, 0, 0, 0, 0, 0})); + CHECK(out.axis(A::LeftX) < -18000 && out.axis(A::LeftX) > -20000); // rescaled + // a square-gate corner (both axes full) stays a full diagonal + map.left_deadzone_percent = 1; + out = map.apply(state({}, {32767, 32767, 0, 0, 0, 0})); + CHECK(out.axis(A::LeftX) == 32767 && out.axis(A::LeftY) == 32767); +} + +static void test_validation() { + std::string why; + GamepadMap map; + map.add({GamepadMapRule::Kind::ButtonToButton, 40, 0, 0, 0}); + CHECK(!map.valid(&why) && why.find("source") != std::string::npos); + // an invalid rule is skipped by apply() instead of reading out of range + CHECK(map.apply(state({B::South})).pressed(B::South)); + map.rules = {GamepadMapRule::axis_to_button(A::LeftX, 0, B::Left)}; + CHECK(!map.valid(&why)); + map.rules = {GamepadMapRule::axis(A::LeftX, A::RightX, 401)}; + CHECK(!map.valid(&why)); + map.rules = {{GamepadMapRule::Kind::ButtonToAxis, 0, 6, 0, 0}}; // axis 6 does not exist + CHECK(!map.valid(&why)); + map.rules = {{GamepadMapRule::Kind::ButtonToButton, 0, 1, 0x80, 0}}; + CHECK(!map.valid(&why)); // unknown flag + map.rules.assign(GamepadMap::MAX_RULES + 1, GamepadMapRule::button(B::South, B::East)); + CHECK(!map.valid(&why) && why == "too many rules"); + map.rules.clear(); + map.right_deadzone_percent = 91; + CHECK(!map.valid(&why)); +} + +static void test_aliasing() { + GamepadMap map; + map.swap(B::South, B::East); + auto s = state({B::South}); + map.apply(s, s); + CHECK(s.pressed(B::East) && !s.pressed(B::South)); +} + +// BSP-D8 (ShanWan BM-769) in its Android mode, as reported over BLE: the +// decoder + the conversion give a usable state, and a map applies on top. +static void test_hid_rp_bridge() { + const char *hex = + "050c0901a1018503751095011501269c0219012a9c028100c005010905a10185040901a1000930093109320935" + "150026ff00750895048102c00939150025073500463b016514750495018142750495018101050919012910150025" + "017501951081020502150026ff0009c409c5950275088102750895018101c0"; + std::vector desc; + for (const char *p = hex; p[0] && p[1]; p += 2) + desc.push_back(static_cast(std::stoi(std::string(p, 2), nullptr, 16))); + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + decoder.set_combine_controls(false); + // A pressed, hat up, right trigger full, left stick full right + const std::vector pad{0xff, 0x80, 0x80, 0x80, 0x00, 0x01, 0x00, 0xff, 0x00, 0x00}; + espp::hid_rp::GamepadReport r; + CHECK(decoder.update(4, pad, r)); + auto s = espp::to_gamepad_state(r); + CHECK(s.pressed(B::South) && s.pressed(B::Up)); + CHECK(s.axis(A::RightTrigger) > 32000 && s.axis(A::LeftX) > 32000); + CHECK(!s.pressed(B::R2) && !s.pressed(B::Right)); // nothing combined + + // a Nintendo-style host: A is east + GamepadMap nintendo; + nintendo.swap(B::South, B::East).triggers_to_buttons(); + s = nintendo.apply(s); + CHECK(s.pressed(B::East) && !s.pressed(B::South) && s.pressed(B::R2)); +} + +static void test_profiles() { + namespace fs = std::filesystem; + const fs::path dir = fs::temp_directory_path() / "gamepad_map_host_test"; + fs::remove_all(dir); + fs::create_directories(dir); + const fs::path file = dir / "profiles.bin"; + std::error_code ec; + + GamepadMap legacy; // e.g. migrated from an application's old settings + legacy.invert(A::LeftY); + { + espp::GamepadProfiles profiles({.file_path = file, .default_map = legacy}); + CHECK(profiles.default_map() == legacy); // no file yet: the configured default + CHECK(!fs::exists(file)); // ... and nothing written until a change + CHECK(profiles.map_for(0x1949, 0x0402) == legacy); + + GamepadMap bsp; + bsp.swap(B::South, B::East); + CHECK(profiles.set_profile({.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp}, ec)); + CHECK(!ec && fs::exists(file)); + CHECK(profiles.map_for(0x1949, 0x0402) == bsp); + CHECK(profiles.map_for(0x045e, 0x0b13) == legacy); + + GamepadMap named; + named.left_deadzone_percent = 12; + CHECK(profiles.set_profile({.vid = 0, .pid = 0, .name = "NoPnP", .map = named}, ec)); + CHECK(profiles.map_for(0, 0, "NoPnP") == named); + CHECK(profiles.map_for(0, 0, "Other") == legacy); + CHECK(!profiles.set_profile({.vid = 0, .pid = 0, .name = "", .map = named}, ec)); + CHECK(ec == std::errc::invalid_argument); + + GamepadMap bad; + bad.right_deadzone_percent = 99; + CHECK(!profiles.set_profile({.vid = 1, .pid = 2, .name = "x", .map = bad}, ec)); + CHECK(ec == std::errc::invalid_argument); + CHECK(!profiles.set_default_map(bad, ec)); + + // replacing keeps one entry per controller + bsp.rules.clear(); + CHECK(profiles.set_profile({.vid = 0x1949, .pid = 0x0402, .name = "BSP-D8", .map = bsp}, ec)); + CHECK(profiles.profiles().size() == 2); + } + { + // reloaded from the file + espp::GamepadProfiles profiles({.file_path = file, .default_map = GamepadMap{}}); + CHECK(profiles.default_map() == legacy); // the stored default, not the configured one + CHECK(profiles.profiles().size() == 2); + CHECK(profiles.map_for(0x1949, 0x0402).rules.empty()); + CHECK(profiles.erase_profile(0x1949, 0x0402, "", ec) && !ec); + CHECK(!profiles.erase_profile(0x1949, 0x0402, "", ec) && !ec); // already gone + CHECK(profiles.map_for(0x1949, 0x0402) == legacy); + } + { + espp::GamepadProfiles profiles({.file_path = file, .max_profiles = 1}); + CHECK(!profiles.load_error()); + CHECK(profiles.profile_count() == 1 && profiles.has_profile(0, 0, "NoPnP")); + CHECK(!profiles.has_profile(0x1949, 0x0402)); + CHECK(profiles.profiles().size() == 1); // NoPnP + CHECK(!profiles.set_profile({.vid = 5, .pid = 6, .name = "full", .map = {}}, ec)); + CHECK(ec == std::errc::no_buffer_space); + CHECK(profiles.reset(ec) && profiles.profiles().empty() && + profiles.default_map().is_identity()); + } + { + // names are stored cut to MAX_NAME_LENGTH and still match by name + espp::GamepadProfiles profiles({.file_path = file}); + const std::string long_name(100, 'n'); + CHECK(profiles.set_profile({.vid = 0, .pid = 0, .name = long_name, .map = {}}, ec)); + CHECK(profiles.has_profile(0, 0, long_name)); + CHECK(profiles.profiles().back().name.size() == espp::GamepadProfile::MAX_NAME_LENGTH); + } + { + // a file that cannot be read is set aside, never overwritten + { + std::ofstream garbage(file, std::ios::binary | std::ios::trunc); + garbage << "definitely not a profile store"; + } + espp::GamepadProfiles profiles({.file_path = file}); + CHECK(profiles.load_error()); + CHECK(fs::exists(fs::path(file.string() + ".unreadable"))); + CHECK(!fs::exists(file)); + CHECK(profiles.profiles().empty()); + CHECK(profiles.set_default_map(GamepadMap{}, ec) && fs::exists(file)); + CHECK(fs::exists(fs::path(file.string() + ".unreadable"))); // still there + } + { + // stored entries are sanitized: an invalid rule is dropped (the rest of + // its map kept), a profile nothing can match is dropped + espp::GamepadProfiles::Data d; + GamepadMap m; + m.add(GamepadMapRule::button(B::South, B::East)); + m.add({GamepadMapRule::Kind::ButtonToButton, 99, 0, 0, 0}); // invalid source + d.profiles.push_back({.vid = 1, .pid = 2, .name = "ok", .map = m}); + d.profiles.push_back({.vid = 0, .pid = 0, .name = "", .map = {}}); // unmatchable + espp::GamepadProfiles::Storage raw({.file_path = file, .auto_load = false}); + CHECK(raw.save(d, ec)); + espp::GamepadProfiles profiles({.file_path = file}); + CHECK(!profiles.load_error()); + CHECK(profiles.profile_count() == 1); + const auto kept = profiles.profile(1, 2); + CHECK(kept.has_value() && kept->map.rules.size() == 1 && kept->map.valid()); + } + fs::remove_all(dir); +} + +int main() { + test_state(); + test_identity(); + test_swap_and_disable(); + test_keep_source_and_or(); + test_axis_to_button(); + test_button_to_axis(); + test_axis_to_axis(); + test_deadzone(); + test_validation(); + test_aliasing(); + test_hid_rp_bridge(); + test_profiles(); + if (failures == 0) { + std::printf("gamepad_map_host_test: all checks passed\n"); + return 0; + } + std::printf("gamepad_map_host_test: %d failure(s)\n", failures); + return 1; +} diff --git a/components/hid-rp/include/hid-rp-report-map.hpp b/components/hid-rp/include/hid-rp-report-map.hpp index 7f0910a72b..6f0b38c717 100644 --- a/components/hid-rp/include/hid-rp-report-map.hpp +++ b/components/hid-rp/include/hid-rp-report-map.hpp @@ -302,11 +302,13 @@ class ReportMap { /// HID usage pages / IDs the decoders look at. namespace usage { constexpr uint16_t PAGE_GENERIC_DESKTOP = 0x01; +constexpr uint16_t PAGE_SIMULATION = 0x02; constexpr uint16_t PAGE_KEYBOARD = 0x07; constexpr uint16_t PAGE_BUTTON = 0x09; constexpr uint16_t PAGE_CONSUMER = 0x0C; constexpr uint16_t GD_X = 0x30, GD_Y = 0x31, GD_Z = 0x32, GD_RX = 0x33, GD_RY = 0x34, GD_RZ = 0x35; constexpr uint16_t GD_WHEEL = 0x38, GD_HAT = 0x39; +constexpr uint16_t SIM_ACCELERATOR = 0xC4, SIM_BRAKE = 0xC5; constexpr uint16_t GD_DPAD_UP = 0x90, GD_DPAD_DOWN = 0x91, GD_DPAD_RIGHT = 0x92, GD_DPAD_LEFT = 0x93; constexpr uint16_t CONSUMER_MENU = 0x0040, CONSUMER_RECORD = 0x00B2, CONSUMER_AC_EXIT = 0x0204, @@ -326,20 +328,56 @@ struct GamepadReport { int32_t hat{-1}; ///< raw hat value (-1 when absent) uint64_t buttons{0}; ///< raw: bit n = button usage n pressed (usages 1..63) uint16_t consumer[4]{0, 0, 0, 0}; ///< raw consumer-page usages active + int16_t lt{0}, rt{0}; ///< analog triggers, 0..32767 (0 on a pad without them) + bool capture{false}; ///< Share / Capture (consumer Record) }; /// Decodes gamepad reports. Face-button numbering differs between controller /// families, so the decoder carries a layout: -/// - Xbox-style: 1 = south, 2 = east, 3 = west, 4 = north (default) -/// - DirectInput / DualShock: 1 = west, 2 = south, 3 = east, 4 = north -/// (picked when the descriptor has a hat switch and >= 13 buttons) -/// Always: 5/6 = L1/R1, 7/8 = L2/R2, 9 = select, 10 = start, 11/12 = L3/R3. -/// Consumer-page controls (Menu, AC Back/Home, Record, AC Properties/Exit as -/// sent by Xbox-style pads) map to start / select / home. Per-device quirks -/// are keyed on VID/PID (apply_quirks()). +/// - Xbox-style: 1 = south, 2 = east, 3 = west, 4 = north, 5/6 = L1/R1, +/// 7/8 = L2/R2, 9 = select, 10 = start, 11/12 = L3/R3 (default) +/// - DirectInput / DualShock: 1 = west, 2 = south, 3 = east, 4 = north, the +/// rest as Xbox-style (picked when the descriptor has a hat switch and >= 13 +/// buttons) +/// Both: 13 = home (the PS button on a DualShock / DualSense). +/// - Android: 1 = south, 2 = east, 4 = west, 5 = north, 7/8 = L1/R1, +/// 9/10 = L2/R2, 11 = select, 12 = start, 13 = home, 14/15 = L3/R3: the +/// layout of BLE HID gamepads (Xbox Wireless over BLE, and the Android modes +/// of 8BitDo / ShanWan pads), picked when the descriptor reports its triggers +/// on the Simulation page (Brake / Accelerator), as those pads do +/// The sticks come from X/Y (left) and Z/Rz (right) when the pad has both Z and +/// Rz, its Rx/Ry then being the analog triggers (DualShock); otherwise the +/// right stick is Rx/Ry (Z without Rz: Z is its X). Simulation-page Brake / +/// Accelerator are the left / right analog triggers. Consumer-page controls +/// (Menu, AC Back/Home, Record, AC Properties/Exit as sent by Xbox-style pads) +/// map to start / select / home. Per-device quirks are keyed on VID/PID +/// (apply_quirks()). +/// +/// By default related controls are combined the way an emulator wants: the +/// left stick also drives the d-pad and the analog triggers also press L2/R2 +/// (both past 40% of their travel), and Share / Capture (consumer Record) also +/// presses Home. A pass-through (a controller bridge, a remapper) turns that off +/// with set_combine_controls(false) so every control reports only itself. +/// +/// A device may spread its state over several input reports (a BLE pad sending +/// its gamepad in report 4 and its consumer keys in report 3, say): update() +/// keeps the latest report of each ID and decodes them together, so a report +/// that carries only some controls does not reset the others. class GamepadDecoder { public: - enum class Layout { Xbox, DirectInput }; + enum class Layout { Xbox, DirectInput, Android }; + /// Human-readable name of a layout (for logs). + static constexpr const char *layout_name(Layout layout) { + switch (layout) { + case Layout::Xbox: + return "Xbox-style"; + case Layout::DirectInput: + return "DirectInput"; + case Layout::Android: + return "Android"; + } + return "?"; + } struct Quirks { Layout layout{Layout::Xbox}; bool dpad_updown_swapped{false}; ///< usages 0x90/0x91 carry down/up @@ -352,16 +390,45 @@ class GamepadDecoder { explicit GamepadDecoder(ReportMap map) : map_(std::move(map)) { size_t buttons = 0; - bool hat = false; + bool hat = false, z = false, rz = false, rx = false, ry = false, sim_triggers = false; for (const auto &f : map_.fields()) { if (f.usage_page == usage::PAGE_BUTTON && !f.array) buttons++; - if (f.usage_page == usage::PAGE_GENERIC_DESKTOP && f.usage == usage::GD_HAT) - hat = true; + if (f.usage_page == usage::PAGE_SIMULATION && + (f.usage == usage::SIM_ACCELERATOR || f.usage == usage::SIM_BRAKE)) + sim_triggers = true; + if (f.usage_page != usage::PAGE_GENERIC_DESKTOP || f.relative) + continue; + hat |= f.usage == usage::GD_HAT; + z |= f.usage == usage::GD_Z; + rz |= f.usage == usage::GD_RZ; + rx |= f.usage == usage::GD_RX; + ry |= f.usage == usage::GD_RY; } - if (hat && buttons >= 13) { + if (sim_triggers) { + quirks_.layout = Layout::Android; + } else if (hat && buttons >= 13) { quirks_.layout = Layout::DirectInput; } + // What each field is, worked out once: decode() then only switches on it. + const bool z_rz_stick = z && rz; + roles_.reserve(map_.fields().size()); + slots_.reserve(map_.fields().size()); + for (const auto &f : map_.fields()) { + const Role role = role_of(f, z_rz_stick, rx, ry, sim_triggers); + roles_.push_back(role); + auto it = std::find(report_ids_.begin(), report_ids_.end(), f.report_id); + if (it == report_ids_.end()) { + report_ids_.push_back(f.report_id); + mapped_.push_back(false); + it = report_ids_.end() - 1; + } + const auto slot = static_cast(it - report_ids_.begin()); + slots_.push_back(slot); + if (role != Role::None) + mapped_[slot] = true; + } + latest_.resize(report_ids_.size()); } /// Whether a map looks like a gamepad (buttons plus a direction source). @@ -405,108 +472,343 @@ class GamepadDecoder { Quirks &quirks() { return quirks_; } const ReportMap &map() const { return map_; } + /// Whether related controls are combined: the left stick also drives the + /// d-pad, the analog triggers also press L2/R2 and Capture also presses Home + /// (default true; see the class description). + void set_combine_controls(bool enabled) { combine_controls_ = enabled; } + bool combine_controls() const { return combine_controls_; } + /// Decode a raw report (with its ID byte, if the device uses IDs). Returns /// false when the report carries none of the mapped fields. bool decode(std::span raw, GamepadReport &out) const { const auto [id, report] = map_.split(raw); + return decode(id, report, out); + } + + /// Decode one report given its ID separately, `payload` excluding any ID + /// byte (how BLE HID delivers reports: the ID comes from the characteristic's + /// Report Reference). The ID is ignored for a device without report IDs. + /// Returns false when the report carries none of the mapped fields. + bool decode(uint8_t report_id, std::span payload, GamepadReport &out) const { + const uint8_t id = map_.uses_report_ids() ? report_id : 0; + const auto &fields = map_.fields(); + return decode_impl( + [&fields, id, payload](size_t field) { + return fields[field].report_id == id ? payload : std::span{}; + }, + out); + } + + /// Remember `payload` as the latest report `report_id` (no ID byte, as for + /// decode(report_id, payload, out)), then decode the latest report of every + /// ID together into `out`. Returns false, leaving `out` alone, when no + /// gamepad control lives in that report (another ID, or e.g. a battery + /// report): only a report that can change the pad's state re-decodes it. + /// Not thread-safe: feed one decoder from one task. A report of a size seen + /// before is stored without allocating. + bool update(uint8_t report_id, std::span payload, GamepadReport &out) { + const uint8_t id = map_.uses_report_ids() ? report_id : 0; + const auto it = std::find(report_ids_.begin(), report_ids_.end(), id); + if (it == report_ids_.end()) + return false; + const auto slot = static_cast(it - report_ids_.begin()); + if (!mapped_[slot]) + return false; + latest_[slot].assign(payload.begin(), payload.end()); + return decode_impl( + [this](size_t field) { return std::span(latest_[slots_[field]]); }, out); + } + + /// Forget the reports update() remembered (e.g. when the device disconnects). + void reset() { + for (auto &r : latest_) + r.clear(); + } + +private: + enum class Role : uint8_t { + None, + Button, + Hat, + DpadUp, + DpadDown, + DpadRight, + DpadLeft, + LeftX, + LeftY, + RightX, + RightY, + LeftTrigger, + RightTrigger, + Consumer, + }; + + static Role role_of(const ReportField &f, bool z_rz_stick, bool has_rx, bool has_ry, + bool sim_triggers) { + if (f.usage_page == usage::PAGE_BUTTON) + return f.array ? Role::None : Role::Button; + if (f.usage_page == usage::PAGE_CONSUMER) + return Role::Consumer; + const bool axis = !f.relative && !f.array && f.logical_max > f.logical_min; + if (f.usage_page == usage::PAGE_SIMULATION && axis) { + if (f.usage == usage::SIM_BRAKE) + return Role::LeftTrigger; + if (f.usage == usage::SIM_ACCELERATOR) + return Role::RightTrigger; + return Role::None; + } + if (f.usage_page != usage::PAGE_GENERIC_DESKTOP) + return Role::None; + switch (f.usage) { + case usage::GD_HAT: + return Role::Hat; + case usage::GD_DPAD_UP: + return Role::DpadUp; + case usage::GD_DPAD_DOWN: + return Role::DpadDown; + case usage::GD_DPAD_RIGHT: + return Role::DpadRight; + case usage::GD_DPAD_LEFT: + return Role::DpadLeft; + default: + break; + } + if (!axis) + return Role::None; + switch (f.usage) { + case usage::GD_X: + return Role::LeftX; + case usage::GD_Y: + return Role::LeftY; + case usage::GD_Z: + // Z is the right stick's X with Rz as its Y, else when there is no Rx + return z_rz_stick || !has_rx ? Role::RightX : Role::None; + case usage::GD_RZ: + return z_rz_stick || !has_ry ? Role::RightY : Role::None; + case usage::GD_RX: + // with Z/Rz as the right stick, Rx/Ry are the triggers (DualShock) unless + // the triggers are on the Simulation page + if (z_rz_stick) + return sim_triggers ? Role::None : Role::LeftTrigger; + return Role::RightX; + case usage::GD_RY: + if (z_rz_stick) + return sim_triggers ? Role::None : Role::RightTrigger; + return Role::RightY; + default: + return Role::None; + } + } + + // Which position a Button-page usage is, for the current layout. + enum class Pos : uint8_t { + None, + South, + East, + West, + North, + L1, + R1, + L2, + R2, + L3, + R3, + Select, + Start, + Home + }; + static Pos position_of(Layout layout, uint16_t button) { + if (layout == Layout::Android) { + switch (button) { + case 1: + return Pos::South; + case 2: + return Pos::East; + case 4: + return Pos::West; + case 5: + return Pos::North; + case 7: + return Pos::L1; + case 8: + return Pos::R1; + case 9: + return Pos::L2; + case 10: + return Pos::R2; + case 11: + return Pos::Select; + case 12: + return Pos::Start; + case 13: + return Pos::Home; + case 14: + return Pos::L3; + case 15: + return Pos::R3; + default: + return Pos::None; + } + } + const bool xbox = layout == Layout::Xbox; + switch (button) { + case 1: + return xbox ? Pos::South : Pos::West; + case 2: + return xbox ? Pos::East : Pos::South; + case 3: + return xbox ? Pos::West : Pos::East; + case 4: + return Pos::North; + case 5: + return Pos::L1; + case 6: + return Pos::R1; + case 7: + return Pos::L2; + case 8: + return Pos::R2; + case 9: + return Pos::Select; + case 10: + return Pos::Start; + case 11: + return Pos::L3; + case 12: + return Pos::R3; + case 13: + return Pos::Home; + default: + return Pos::None; + } + } + + static int16_t stick_value(const ReportField &f, int32_t v) { + // 64-bit throughout: a full 32-bit logical range overflows int32_t + const int64_t range = static_cast(f.logical_max) - f.logical_min; + const int64_t centered = 2 * (static_cast(v) - f.logical_min) - range; + return static_cast(std::clamp(centered * 32767 / range, -32767, 32767)); + } + static int16_t trigger_value(const ReportField &f, int32_t v) { + const int64_t range = static_cast(f.logical_max) - f.logical_min; + const int64_t from_min = static_cast(v) - f.logical_min; + return static_cast(std::clamp(from_min * 32767 / range, 0, 32767)); + } + + // `payload_for(field index)` gives the payload holding that field's report + // (empty when there is none to decode). + template + bool decode_impl(PayloadFor payload_for, GamepadReport &out) const { GamepadReport r{}; bool any = false; - const bool xbox = quirks_.layout == Layout::Xbox; - const uint16_t south = xbox ? 1 : 2, east = xbox ? 2 : 3, west = xbox ? 3 : 1, north = 4; size_t n_consumer = 0; - for (const auto &f : map_.fields()) { - const auto v = ReportMap::extract(f, id, report); + const auto &fields = map_.fields(); + for (size_t i = 0; i < fields.size(); i++) { + const auto &f = fields[i]; + const Role role = roles_[i]; + if (role == Role::None) + continue; + const auto payload = payload_for(i); + if (payload.empty()) + continue; + const auto v = ReportMap::extract(f, f.report_id, payload); if (!v) continue; any = true; - if (f.usage_page == usage::PAGE_BUTTON && !f.array) { + switch (role) { + case Role::Button: { const bool pressed = *v != 0; if (pressed && f.usage >= 1 && f.usage < 64) r.buttons |= uint64_t{1} << f.usage; - if (f.usage == south) + switch (position_of(quirks_.layout, f.usage)) { + case Pos::South: r.south |= pressed; - else if (f.usage == east) + break; + case Pos::East: r.east |= pressed; - else if (f.usage == west) + break; + case Pos::West: r.west |= pressed; - else if (f.usage == north) + break; + case Pos::North: r.north |= pressed; - else if (f.usage == 5) + break; + case Pos::L1: r.l1 |= pressed; - else if (f.usage == 6) + break; + case Pos::R1: r.r1 |= pressed; - else if (f.usage == 7) + break; + case Pos::L2: r.l2 |= pressed; - else if (f.usage == 8) + break; + case Pos::R2: r.r2 |= pressed; - else if (f.usage == 9) - r.select |= pressed; - else if (f.usage == 10) - r.start |= pressed; - else if (f.usage == 11) + break; + case Pos::L3: r.l3 |= pressed; - else if (f.usage == 12) + break; + case Pos::R3: r.r3 |= pressed; - } else if (f.usage_page == usage::PAGE_GENERIC_DESKTOP) { - if (f.usage == usage::GD_HAT) { - r.hat = *v; - const int32_t dir = - *v - f.logical_min; // 0 = up, clockwise; 8 (or out of range) = centered - if (*v >= f.logical_min && *v <= f.logical_max && dir >= 0 && dir < 8) { - r.up |= dir == 7 || dir == 0 || dir == 1; - r.right |= dir >= 1 && dir <= 3; - r.down |= dir >= 3 && dir <= 5; - r.left |= dir >= 5; - } - } else if (f.usage >= usage::GD_DPAD_UP && f.usage <= usage::GD_DPAD_LEFT) { - const bool pressed = *v != 0; - switch (f.usage) { - case usage::GD_DPAD_UP: - (quirks_.dpad_updown_swapped ? r.down : r.up) |= pressed; - break; - case usage::GD_DPAD_DOWN: - (quirks_.dpad_updown_swapped ? r.up : r.down) |= pressed; - break; - case usage::GD_DPAD_RIGHT: - r.right |= pressed; - break; - case usage::GD_DPAD_LEFT: - r.left |= pressed; - break; - default: - break; - } - } else if (f.usage >= usage::GD_X && f.usage <= usage::GD_RZ && !f.relative && - f.logical_max > f.logical_min) { - // 64-bit throughout: a full 32-bit logical range overflows int32_t - const int64_t range = static_cast(f.logical_max) - f.logical_min; - const int64_t centered = 2 * (static_cast(*v) - f.logical_min) - range; - int16_t n = - static_cast(std::clamp(centered * 32767 / range, -32767, 32767)); - const bool vertical = - f.usage == usage::GD_Y || f.usage == usage::GD_RZ || f.usage == usage::GD_RY; - if (vertical && quirks_.y_up_positive) - n = static_cast(-n); - switch (f.usage) { - case usage::GD_X: - r.lx = n; - break; - case usage::GD_Y: - r.ly = n; - break; - case usage::GD_Z: - case usage::GD_RX: - r.rx = n; - break; - case usage::GD_RZ: - case usage::GD_RY: - r.ry = n; - break; - default: - break; - } + break; + case Pos::Select: + r.select |= pressed; + break; + case Pos::Start: + r.start |= pressed; + break; + case Pos::Home: + r.home |= pressed; + break; + case Pos::None: + break; } - } else if (f.usage_page == usage::PAGE_CONSUMER) { + break; + } + case Role::Hat: { + r.hat = *v; + const int32_t dir = *v - f.logical_min; // 0 = up, clockwise; 8 (or out of range) = centered + if (*v >= f.logical_min && *v <= f.logical_max && dir >= 0 && dir < 8) { + r.up |= dir == 7 || dir == 0 || dir == 1; + r.right |= dir >= 1 && dir <= 3; + r.down |= dir >= 3 && dir <= 5; + r.left |= dir >= 5; + } + break; + } + case Role::DpadUp: + (quirks_.dpad_updown_swapped ? r.down : r.up) |= *v != 0; + break; + case Role::DpadDown: + (quirks_.dpad_updown_swapped ? r.up : r.down) |= *v != 0; + break; + case Role::DpadRight: + r.right |= *v != 0; + break; + case Role::DpadLeft: + r.left |= *v != 0; + break; + case Role::LeftX: + r.lx = stick_value(f, *v); + break; + case Role::LeftY: + r.ly = + quirks_.y_up_positive ? static_cast(-stick_value(f, *v)) : stick_value(f, *v); + break; + case Role::RightX: + r.rx = stick_value(f, *v); + break; + case Role::RightY: + r.ry = + quirks_.y_up_positive ? static_cast(-stick_value(f, *v)) : stick_value(f, *v); + break; + case Role::LeftTrigger: + r.lt = trigger_value(f, *v); + break; + case Role::RightTrigger: + r.rt = trigger_value(f, *v); + break; + case Role::Consumer: { uint16_t u = 0; if (f.array) { if (*v == f.logical_min && (f.usage != 0 || f.logical_min != 0)) @@ -531,29 +833,46 @@ class GamepadDecoder { r.select = true; break; case usage::CONSUMER_AC_HOME: - case usage::CONSUMER_RECORD: r.home = true; break; + case usage::CONSUMER_RECORD: + r.capture = true; + break; default: break; } + break; + } + case Role::None: + break; } } - // the left stick as a d-pad with a 40% dead zone - constexpr int16_t DEAD = 32767 * 2 / 5; - r.left |= r.lx < -DEAD; - r.right |= r.lx > DEAD; - r.up |= r.ly < -DEAD; - r.down |= r.ly > DEAD; if (!any) return false; + if (combine_controls_) { + // the left stick as a d-pad and the analog triggers as L2 / R2, with a + // 40% dead zone; Capture as Home + r.home |= r.capture; + constexpr int16_t DEAD = 32767 * 2 / 5; + r.left |= r.lx < -DEAD; + r.right |= r.lx > DEAD; + r.up |= r.ly < -DEAD; + r.down |= r.ly > DEAD; + r.l2 |= r.lt > DEAD; + r.r2 |= r.rt > DEAD; + } out = r; return true; } -private: ReportMap map_; Quirks quirks_{}; + bool combine_controls_{true}; + std::vector roles_; ///< per field of map_ + std::vector report_ids_; ///< the IDs the fields live in + std::vector mapped_; ///< per report_ids_ entry: carries a gamepad control + std::vector slots_; ///< per field of map_: its report_ids_ index + std::vector> latest_; ///< update(): latest payload per report_ids_ entry }; /// A keyboard report: which usages (HID keyboard page, 0..255 incl. the diff --git a/components/hid-rp/test/hid_rp_report_map_host_test.cpp b/components/hid-rp/test/hid_rp_report_map_host_test.cpp index 7cbcbbdf17..d068eda40a 100644 --- a/components/hid-rp/test/hid_rp_report_map_host_test.cpp +++ b/components/hid-rp/test/hid_rp_report_map_host_test.cpp @@ -1,7 +1,7 @@ // Host-buildable unit tests for the runtime report map / decoders // (hid-rp-report-map.hpp). Build & run: // -// c++ -std=c++23 -Wall -Wextra -Werror \ +// c++ -std=c++23 -Wall -Wextra -Werror -Wno-comment \ // -isystem components/hid-rp/include \ // -isystem components/hid-rp/detail/hid-rp/hid-rp \ // -isystem components/format/include \ @@ -14,12 +14,14 @@ #include #include +#include #include #include #include "hid-rp-gamepad.hpp" #include "hid-rp-report-map.hpp" #include "hid-rp-switch-pro.hpp" +#include "hid-rp-xbox.hpp" static int failures = 0; #define CHECK(cond) \ @@ -64,11 +66,12 @@ static void test_generated_gamepad() { // Build a report with the generator, decode it with the mapper. Gamepad report; report.reset(); - report.set_button(2, true); // Xbox-style: 2 = east - report.set_button(10, true); // start + report.set_button(2, true); // Android numbering: 2 = east + report.set_button(12, true); // start report.set_hat(espp::gamepad::Hat::UP); report.set_left_joystick(-1.0f, 0.0f); report.set_right_joystick(0.0f, 1.0f); + report.set_accelerator(1.0f); auto bytes = report.get_report(); std::vector raw(bytes.begin(), bytes.end()); if (map->uses_report_ids()) { @@ -77,10 +80,9 @@ static void test_generated_gamepad() { espp::hid_rp::GamepadDecoder decoder(*map); CHECK(decoder.looks_like_gamepad()); - // a hat plus 16 buttons reads as a DualShock-style pad to the heuristic; - // pin the layout the assertions below assume - CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::DirectInput); - decoder.quirks().layout = espp::hid_rp::GamepadDecoder::Layout::Xbox; + // Simulation-page triggers (Brake / Accelerator) read as an Android-layout + // pad: the numbering espp's own BLE gamepads (and the Xbox over BLE) use + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::Android); espp::hid_rp::GamepadReport g; CHECK(decoder.decode(raw, g)); CHECK(g.east); @@ -90,6 +92,158 @@ static void test_generated_gamepad() { CHECK(g.lx < -30000); CHECK(g.left); // full left stick deflection also reads as d-pad left CHECK(g.ry > 30000); + CHECK(g.rt > 32000 && g.lt == 0); + CHECK(g.r2 && !g.l2); // ... and the full trigger as R2 + + // a pass-through decoder reports every control only as itself + decoder.set_combine_controls(false); + CHECK(decoder.decode(raw, g)); + CHECK(!g.left && g.lx < -30000); + CHECK(!g.r2 && g.rt > 32000); + CHECK(g.up); // the hat itself still is the d-pad +} + +// BSP-D8 (ShanWan BM-769) in its Android mode, descriptor as the device +// reports it over BLE: report 3 = consumer keys, report 4 = gamepad with 8-bit +// X/Y/Z/Rz sticks, a 4-bit hat (null state), 16 buttons, 8-bit Simulation-page +// Accelerator / Brake triggers. +static std::vector hex_bytes(const char *hex) { + std::vector out; + auto nibble = [](char c) { + return static_cast(c <= '9' ? c - '0' : (c | 0x20) - 'a' + 10); + }; + for (; hex[0] && hex[1]; hex += 2) + out.push_back(static_cast(nibble(hex[0]) << 4 | nibble(hex[1]))); + return out; +} + +static void test_ble_android_pad() { + const auto desc = hex_bytes( + "050c0901a1018503751095011501269c0219012a9c028100c005010905a10185040901a1000930093109320935" + "150026ff00750895048102c00939150025073500463b016514750495018142750495018101050919012910150025" + "017501951081020502150026ff0009c409c5950275088102750895018101c0"); + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + CHECK(map->uses_report_ids()); + CHECK(map->report_bytes(4) == 10); + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + CHECK(decoder.looks_like_gamepad()); + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::Android); + decoder.set_combine_controls(false); + + // BLE delivers the payload without the ID byte; the ID comes from the Report + // Reference. Neutral: sticks at 0x80, hat null (15), nothing pressed. + std::vector pad{0x80, 0x80, 0x80, 0x80, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00}; + espp::hid_rp::GamepadReport g; + CHECK(decoder.decode(4, pad, g)); + CHECK(std::abs(g.lx) < 300 && std::abs(g.ly) < 300); + CHECK(std::abs(g.rx) < 300 && std::abs(g.ry) < 300); // the Xbox parse pegged these + CHECK(!g.up && !g.down && !g.left && !g.right); + CHECK(g.buttons == 0 && g.lt == 0 && g.rt == 0); + + // A (button 1), Y (button 5), R1 (button 8), Start (button 12), hat right, + // right stick full left / down, half left trigger, full right trigger + pad = {0x80, 0x80, 0x00, 0xff, 0x02, 0x91, 0x08, 0xff, 0x80, 0x00}; + CHECK(decoder.decode(4, pad, g)); + CHECK(g.south && g.north && !g.east && !g.west); + CHECK(g.r1 && !g.l1); + CHECK(g.start && !g.select); + CHECK(g.right && !g.up && !g.down && !g.left); + CHECK(g.rx < -32000 && g.ry > 32000); + CHECK(g.rt > 32000); // Accelerator (first) = right trigger + CHECK(g.lt > 16000 && g.lt < 16600); // Brake = left trigger, half way + + // the consumer report (3) alone carries no pad state: decode() of it alone + // reports only consumer keys, update() keeps the pad report it last saw + std::vector consumer{0x23, 0x02}; // AC Home + CHECK(decoder.update(4, pad, g)); + CHECK(g.south && g.rt > 32000); + CHECK(decoder.update(3, consumer, g)); + CHECK(g.home); + CHECK(g.south && g.rt > 32000); // still there + CHECK(!decoder.update(9, pad, g)); // not a report of this device + decoder.reset(); + CHECK(decoder.update(3, consumer, g)); + CHECK(g.home && !g.south); +} + +// espp's Xbox Wireless (BLE) report: X/Y/Z/Rz 16-bit sticks, Simulation +// triggers, Android button numbering (A = 1, B = 2, X = 4, Y = 5, ...). +static void test_xbox_ble() { + auto rdf = espp::xbox_descriptor(); + std::vector desc(rdf.begin(), rdf.end()); + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::Android); + decoder.set_combine_controls(false); + espp::XboxGamepadInputReport<> report; + report.reset(); + report.set_button_x(true); + report.set_button_l3(true); + report.set_button_menu(true); + report.set_left_joystick(0.0f, -1.0f); + report.set_brake(1.0f); + auto bytes = report.get_report(); + std::vector payload(bytes.begin(), bytes.end()); + espp::hid_rp::GamepadReport g; + CHECK(decoder.decode(espp::XboxGamepadInputReport<>::ID, payload, g)); + CHECK(g.west && !g.south && !g.north && !g.east); + CHECK(g.l3 && !g.r3); + CHECK(g.start); + CHECK(g.ly < -30000 && std::abs(g.lx) < 300); + CHECK(g.lt > 32000 && g.rt == 0); + + // the battery report carries no gamepad control: update() ignores it (and + // leaves `out` alone) rather than re-sending the last pad state + CHECK(decoder.update(espp::XboxGamepadInputReport<>::ID, payload, g)); + espp::hid_rp::GamepadReport untouched; + untouched.hat = 1234; + const std::vector battery{0x55}; + CHECK(!decoder.update(espp::XboxBatteryInputReport<>::ID, battery, untouched)); + CHECK(untouched.hat == 1234); +} + +// A DualShock-style descriptor: X/Y/Z/Rz sticks, then Rx/Ry as the analog +// triggers (the pre-Android decoder read Rx over the right stick's X). +static void test_dualshock_axes() { + // usage page GD, gamepad, app collection, report id 1, X Y Z Rz 8-bit, + // hat, 14 buttons, padding, Rx Ry 8-bit + const std::vector desc{ + 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01, // GD, gamepad, app, id 1 + 0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, // X Y Z Rz + 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02, // 4 x u8 + 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, // hat + 0x05, 0x09, 0x19, 0x01, 0x29, 0x0e, 0x15, 0x00, 0x25, 0x01, // buttons 1..14 + 0x75, 0x01, 0x95, 0x0e, 0x81, 0x02, // + 0x75, 0x06, 0x95, 0x01, 0x81, 0x01, // pad to a byte + 0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xff, 0x00, // Rx Ry + 0x75, 0x08, 0x95, 0x02, 0x81, 0x02, 0xc0}; + auto map = espp::hid_rp::ReportMap::parse(desc); + CHECK(map.has_value()); + if (!map) + return; + espp::hid_rp::GamepadDecoder decoder(std::move(*map)); + CHECK(decoder.quirks().layout == espp::hid_rp::GamepadDecoder::Layout::DirectInput); + // right stick full right, left trigger full, right trigger released + // byte 4 = hat (null, 8) in the low nibble + buttons 1..4 above it (2 = 0x20) + const std::vector raw{0x01, 0x80, 0x80, 0xff, 0x80, 0x28, 0x00, 0x00, 0xff, 0x00}; + espp::hid_rp::GamepadReport g; + CHECK(decoder.decode(raw, g)); + CHECK(g.rx > 32000); // Z, not overwritten by Rx + CHECK(std::abs(g.ry) < 300); + CHECK(g.lt > 32000 && g.rt == 0); + CHECK(g.south); // DirectInput: button 2 = south + CHECK(!g.home); + // button 13 (the PS button): payload bit 36 + 12 = 48 = payload byte 6 (raw[7]) bit 0 + std::vector ps = raw; + ps[7] = 0x01; + CHECK(decoder.decode(ps, g)); + CHECK(g.home); } // The classic boot-protocol keyboard descriptor (8-byte reports: modifier @@ -399,6 +553,9 @@ int main() { test_keyboard_array_logical_min(); test_edge_items(); test_generated_gamepad(); + test_ble_android_pad(); + test_xbox_ble(); + test_dualshock_axes(); test_keyboard(); test_mouse(); test_report_ids_consumer_dpad(); diff --git a/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp b/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp index 6f2b3e3972..b7d424f710 100644 --- a/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp +++ b/components/usb_host/tab5_example/main/usb_host_tab5_example.cpp @@ -163,9 +163,7 @@ extern "C" void app_main(void) { } else if (GamepadDecoder::looks_like_gamepad(*map)) { GamepadDecoder pad(std::move(*map)); pad.apply_quirks(info.vid, info.pid); // per-device layout fixes, by VID:PID - logger.info("gamepad layout: {}", pad.quirks().layout == GamepadDecoder::Layout::Xbox - ? "Xbox-style" - : "DirectInput"); + logger.info("gamepad layout: {}", GamepadDecoder::layout_name(pad.quirks().layout)); iface.decoder = std::move(pad); iface.card.kind = Gui::Kind::Gamepad; } diff --git a/doc/Doxyfile b/doc/Doxyfile index fdc37ad5b4..2ee7bfe390 100755 --- a/doc/Doxyfile +++ b/doc/Doxyfile @@ -131,6 +131,7 @@ EXAMPLE_PATH = \ $(PROJECT_PATH)/components/filters/example/main/filters_example.cpp \ $(PROJECT_PATH)/components/ftp/example/main/ftp_example.cpp \ $(PROJECT_PATH)/components/ft5x06/example/main/ft5x06_example.cpp \ + $(PROJECT_PATH)/components/gamepad_map/example/main/gamepad_map_example.cpp \ $(PROJECT_PATH)/components/gfps_service/example/main/gfps_service_example.cpp \ $(PROJECT_PATH)/components/gps/example/main/gps_example.cpp \ $(PROJECT_PATH)/components/gt911/example/main/gt911_example.cpp \ @@ -353,6 +354,10 @@ INPUT = \ $(PROJECT_PATH)/components/ftp/include/ftp_server.hpp \ $(PROJECT_PATH)/components/ftp/include/ftp_client_session.hpp \ $(PROJECT_PATH)/components/ft5x06/include/ft5x06.hpp \ + $(PROJECT_PATH)/components/gamepad_map/include/gamepad_map.hpp \ + $(PROJECT_PATH)/components/gamepad_map/include/gamepad_profiles.hpp \ + $(PROJECT_PATH)/components/gamepad_map/include/gamepad_state.hpp \ + $(PROJECT_PATH)/components/gamepad_map/include/gamepad_state_hid_rp.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps_characteristic_callbacks.hpp \ $(PROJECT_PATH)/components/gfps_service/include/gfps_service.hpp \ diff --git a/doc/en/input/gamepad_map.rst b/doc/en/input/gamepad_map.rst new file mode 100644 index 0000000000..02e509473d --- /dev/null +++ b/doc/en/input/gamepad_map.rst @@ -0,0 +1,34 @@ +Gamepad Map APIs +**************** + +Gamepad Map +----------- + +The `gamepad_map` component remaps a gamepad's buttons and axes: button to +button, analog to digital (a stick direction or trigger past a threshold), +digital to analog (a button driving an axis) and analog to analog (swap, +invert, scale), plus radial stick dead zones. `GamepadState` names buttons by +position (south / east / west / north) so a map means the same thing for Xbox, +Nintendo and PlayStation controllers. `GamepadProfiles` keeps a default map and +one map per controller type (vendor / product ID) in a file, stored with +`PersistentData`. `to_gamepad_state()` converts the runtime HID decoder's +`hid_rp::GamepadReport`. + +Code examples for the Gamepad Map API are provided in the `gamepad_map` example +folder. + +.. ------------------------------- Example ------------------------------------- + +.. toctree:: + + gamepad_map_example + +.. ---------------------------- API Reference ---------------------------------- + +API Reference +------------- + +.. include-build-file:: inc/gamepad_state.inc +.. include-build-file:: inc/gamepad_map.inc +.. include-build-file:: inc/gamepad_profiles.inc +.. include-build-file:: inc/gamepad_state_hid_rp.inc diff --git a/doc/en/input/gamepad_map_example.md b/doc/en/input/gamepad_map_example.md new file mode 100644 index 0000000000..008f2ff5fa --- /dev/null +++ b/doc/en/input/gamepad_map_example.md @@ -0,0 +1,2 @@ +```{include} ../../../components/gamepad_map/example/README.md +``` diff --git a/doc/en/input/index.rst b/doc/en/input/index.rst index 6f9a5456ed..93e93dd323 100644 --- a/doc/en/input/index.rst +++ b/doc/en/input/index.rst @@ -12,6 +12,7 @@ Input devices button joystick controller + gamepad_map qwiicnes Touch & input drivers diff --git a/lib/espp.cmake b/lib/espp.cmake index 66547e79cb..bbbd7b2050 100644 --- a/lib/espp.cmake +++ b/lib/espp.cmake @@ -295,6 +295,7 @@ set(ESPP_INCLUDES ${ESPP_COMPONENTS}/filters/include ${ESPP_COMPONENTS}/ftp/include ${ESPP_COMPONENTS}/format/include + ${ESPP_COMPONENTS}/gamepad_map/include ${ESPP_COMPONENTS}/hid-rp/include ${ESPP_COMPONENTS}/joystick/include ${ESPP_COMPONENTS}/logger/include diff --git a/lib/include/espp.hpp b/lib/include/espp.hpp index 81e53b3efc..3e57c34fce 100644 --- a/lib/include/espp.hpp +++ b/lib/include/espp.hpp @@ -28,6 +28,10 @@ extern "C" { #include "file_system.hpp" #include "ftp_client_session.hpp" #include "ftp_server.hpp" +#include "gamepad_map.hpp" +#include "gamepad_profiles.hpp" +#include "gamepad_state.hpp" +#include "gamepad_state_formatters.hpp" #include "gaussian.hpp" // TODO: these are not working // #include "hid-rp.hpp"