upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/shims/gameinput.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/shims/gameinput.cpp')
-rw-r--r--runtime/shims/gameinput.cpp96
1 files changed, 84 insertions, 12 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp
index 2b55022f4..3b66e2ab9 100644
--- a/runtime/shims/gameinput.cpp
+++ b/runtime/shims/gameinput.cpp
@@ -50,8 +50,9 @@ using namespace gi;
50 50
51namespace { 51namespace {
52 52
53constexpr uint32_t kSupportedKinds = 53constexpr uint32_t kBaseKinds =
54 GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation; 54 GameInputKindControllerAxis | GameInputKindControllerButton | GameInputKindGamepad | GameInputKindUiNavigation;
55constexpr uint32_t kSupportedKinds = kBaseKinds | GameInputKindMotion; // everything a reading may carry
55constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT 56constexpr uint32_t kAxisCount = 6; // LX, LY, RX, RY, LT, RT
56constexpr uint32_t kButtonCount = SDL_GAMEPAD_BUTTON_COUNT; 57constexpr uint32_t kButtonCount = SDL_GAMEPAD_BUTTON_COUNT;
57constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled; 58constexpr uint32_t kConnectedStatus = GameInputDeviceConnected | GameInputDeviceInputEnabled | GameInputDeviceOutputEnabled;
@@ -61,6 +62,14 @@ constexpr uint64_t kBatteryRefreshUs = 1'000'000;
61constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) 62constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t)
62constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old 63constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old
63constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate 64constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate
65// Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed
66// fractions of the maxima motionInfo reports, so a reading stays within -1..1 however hard the pad is shaken. The
67// maxima are this shim's choice: SDL does not expose a sensor range, and 2 g / 2000 deg/s are the ranges a
68// DualSense's accelerometer and gyro can express (VERIFY: against the game and a real pad, docs/gameinput.md).
69constexpr float kMaxAcceleration = 19.6133f; // 2 g in m/s^2
70constexpr float kMaxAngularVelocity = 34.9066f; // 2000 deg/s in rad/s
71constexpr float kMotionSensorRate = 250.0f; // requested sample rate; the device clamps to what it has
72constexpr uint64_t kMotionReadingUs = 8'000; // a motion pad streams readings at ~125 Hz so the history stays sane
64 73
65uint64_t now_us() { 74uint64_t now_us() {
66 static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }(); 75 static const LARGE_INTEGER freq = [] { LARGE_INTEGER f; QueryPerformanceFrequency(&f); return f; }();
@@ -133,6 +142,8 @@ struct Snapshot {
133 float axes[kAxisCount] = {}; 142 float axes[kAxisCount] = {};
134 bool buttons[kButtonCount] = {}; 143 bool buttons[kButtonCount] = {};
135 bool guide = false; 144 bool guide = false;
145 GameInputMotionState motion{}; // valid only when has_motion; does not take part in operator==
146 bool has_motion = false;
136 bool operator==(const Snapshot& o) const { // field by field: the padding is not initialised 147 bool operator==(const Snapshot& o) const { // field by field: the padding is not initialised
137 const GameInputGamepadState &a = gamepad, &b = o.gamepad; 148 const GameInputGamepadState &a = gamepad, &b = o.gamepad;
138 return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger && 149 return a.buttons == b.buttons && a.leftTrigger == b.leftTrigger && a.rightTrigger == b.rightTrigger &&
@@ -164,7 +175,9 @@ public:
164 return r; 175 return r;
165 } 176 }
166 177
167 uint32_t STDMETHODCALLTYPE GetInputKind() override { return kSupportedKinds; } 178 uint32_t STDMETHODCALLTYPE GetInputKind() override {
179 return s_.has_motion ? kSupportedKinds : kBaseKinds; // a reading of a pad without sensors carries no motion
180 }
168 uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; } 181 uint64_t STDMETHODCALLTYPE GetSequenceNumber(uint32_t) override { return seq_; }
169 uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; } 182 uint64_t STDMETHODCALLTYPE GetTimestamp() override { return ts_; }
170 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; 183 void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override;
@@ -191,7 +204,11 @@ public:
191 bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; } 204 bool STDMETHODCALLTYPE GetMouseState(void*) override { return false; }
192 uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; } 205 uint32_t STDMETHODCALLTYPE GetTouchCount() override { return 0; }
193 uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; } 206 uint32_t STDMETHODCALLTYPE GetTouchState(uint32_t, void*) override { return 0; }
194 bool STDMETHODCALLTYPE GetMotionState(void*) override { return false; } 207 bool STDMETHODCALLTYPE GetMotionState(void* state) override {
208 if (!state || !s_.has_motion) return false;
209 *static_cast<GameInputMotionState*>(state) = s_.motion;
210 return true;
211 }
195 bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; } 212 bool STDMETHODCALLTYPE GetArcadeStickState(void*) override { return false; }
196 bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; } 213 bool STDMETHODCALLTYPE GetFlightStickState(void*) override { return false; }
197 bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override { 214 bool STDMETHODCALLTYPE GetGamepadState(GameInputGamepadState* state) override {
@@ -281,6 +298,7 @@ public:
281 GameInputControllerButtonInfo button_info[kButtonCount]{}; 298 GameInputControllerButtonInfo button_info[kButtonCount]{};
282 GameInputGamepadInfo gamepad_info{}; 299 GameInputGamepadInfo gamepad_info{};
283 GameInputUiNavigationInfo ui_info{}; 300 GameInputUiNavigationInfo ui_info{};
301 GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it
284 std::atomic<uint32_t> status{GameInputDeviceNoStatus}; 302 std::atomic<uint32_t> status{GameInputDeviceNoStatus};
285 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading 303 std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading
286 uint64_t evicted_order = 0; // order of the newest reading dropped from history 304 uint64_t evicted_order = 0; // order of the newest reading dropped from history
@@ -294,9 +312,10 @@ public:
294 SDL_Gamepad* pad = nullptr; 312 SDL_Gamepad* pad = nullptr;
295 SDL_JoystickID id = 0; 313 SDL_JoystickID id = 0;
296 int player = -1; 314 int player = -1;
297 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false; 315 bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false;
298 rt::gameinput::OutputState sent{}; 316 rt::gameinput::OutputState sent{};
299 Snapshot last_snap{}; // what the latest reading holds 317 Snapshot last_snap{}; // what the latest reading holds
318 uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors
300 uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0; 319 uint64_t motors_sent_at = 0, triggers_sent_at = 0, battery_at = 0;
301 bool ds_sent_once = false; 320 bool ds_sent_once = false;
302 321
@@ -446,7 +465,10 @@ uint16_t to_u16(float v) { return static_cast<uint16_t>(std::lround(std::clamp(v
446 465
447float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); } 466float axis(SDL_Gamepad* p, SDL_GamepadAxis a) { return std::max(-1.0f, SDL_GetGamepadAxis(p, a) / 32767.0f); }
448 467
449Snapshot read_pad(SDL_Gamepad* p) { 468float norm(float v, float max) { return std::clamp(v / max, -1.0f, 1.0f); }
469
470Snapshot read_pad(Device* d) {
471 SDL_Gamepad* p = d->pad;
450 Snapshot s; 472 Snapshot s;
451 auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); }; 473 auto down = [p](SDL_GamepadButton b) { return SDL_GetGamepadButton(p, b); };
452 struct Map { SDL_GamepadButton sdl; uint32_t gi; }; 474 struct Map { SDL_GamepadButton sdl; uint32_t gi; };
@@ -486,6 +508,31 @@ Snapshot read_pad(SDL_Gamepad* p) {
486 for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast<SDL_GamepadButton>(i)); 508 for (uint32_t i = 0; i < kButtonCount; ++i) s.buttons[i] = down(static_cast<SDL_GamepadButton>(i));
487 s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE); 509 s.guide = down(SDL_GAMEPAD_BUTTON_GUIDE);
488 510
511 // Motion, normalised against the maxima motionInfo reports (the ABI's fraction convention). Sensors were enabled
512 // when the pad was opened; a pad whose sensor read fails just reports no motion this poll. SDL answers reads
513 // with zeros before the device's first sample arrives, and gravity makes a real accelerometer never read
514 // exactly zero, so all-zero accel means "no sample yet" and the reading carries no motion at all.
515 if (d->has_motion) {
516 float accel[3], gyro[3];
517 if (SDL_GetGamepadSensorData(p, SDL_SENSOR_ACCEL, accel, 3) &&
518 SDL_GetGamepadSensorData(p, SDL_SENSOR_GYRO, gyro, 3) &&
519 (accel[0] != 0.0f || accel[1] != 0.0f || accel[2] != 0.0f)) {
520 s.has_motion = true;
521 s.motion.accelerationX = norm(accel[0], kMaxAcceleration);
522 s.motion.accelerationY = norm(accel[1], kMaxAcceleration);
523 s.motion.accelerationZ = norm(accel[2], kMaxAcceleration);
524 s.motion.angularVelocityX = norm(gyro[0], kMaxAngularVelocity);
525 s.motion.angularVelocityY = norm(gyro[1], kMaxAngularVelocity);
526 s.motion.angularVelocityZ = norm(gyro[2], kMaxAngularVelocity);
527 // SDL's gamepad API has no compass and the shim synthesises no orientation, so those stay zero and
528 // unknown rather than a made-up value.
529 s.motion.accelerometerAccuracy = GameInputMotionAccuracyHigh;
530 s.motion.gyroscopeAccuracy = GameInputMotionAccuracyHigh;
531 s.motion.magnetometerAccuracy = GameInputMotionAccuracyUnknown;
532 s.motion.orientationAccuracy = GameInputMotionAccuracyUnknown;
533 }
534 }
535
489 // UI navigation derived from the gamepad (VERIFY against the console's own mapping). 536 // UI navigation derived from the gamepad (VERIFY against the console's own mapping).
490 const uint32_t b = s.gamepad.buttons; 537 const uint32_t b = s.gamepad.buttons;
491 const float t = 0.5f; 538 const float t = 0.5f;
@@ -544,10 +591,19 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
544 // filters on the family). 591 // filters on the family).
545 i.deviceFamily = GameInputFamilyXboxOne; 592 i.deviceFamily = GameInputFamilyXboxOne;
546 if (SDL_GetGamepadConnectionState(p) == SDL_JOYSTICK_CONNECTION_WIRELESS) i.capabilities |= GameInputDeviceCapabilityWireless; 593 if (SDL_GetGamepadConnectionState(p) == SDL_JOYSTICK_CONNECTION_WIRELESS) i.capabilities |= GameInputDeviceCapabilityWireless;
547 i.supportedInput = kSupportedKinds; 594 // The per-device kind set: the reading-kind searches take the global kSupportedKinds as the outer bound and this
595 // as the per-device one, so only pads with sensors answer a motion query.
596 i.supportedInput = kBaseKinds;
548 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; 597 if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency;
549 if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off)) 598 if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off))
550 i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger; 599 i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger;
600 if (d->has_motion) {
601 i.supportedInput |= GameInputKindMotion;
602 // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has
603 // no compass, and maxMagneticFieldStrength 0 says so (Microsoft's GameInputMotionInfo remarks).
604 d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f};
605 i.motionInfo = &d->motion_info;
606 }
551 i.controllerAxisCount = kAxisCount; 607 i.controllerAxisCount = kAxisCount;
552 i.controllerButtonCount = kButtonCount; 608 i.controllerButtonCount = kButtonCount;
553 for (uint32_t a = 0; a < kAxisCount; ++a) { 609 for (uint32_t a = 0; a < kAxisCount; ++a) {
@@ -583,6 +639,7 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) {
583// the title holds outlive their place here (~Reading only releases the device, which takes no lock). Under g().mu. 639// the title holds outlive their place here (~Reading only releases the device, which takes no lock). Under g().mu.
584Reading* push_reading(Device* d, const Snapshot& snap, uint64_t ts) { 640Reading* push_reading(Device* d, const Snapshot& snap, uint64_t ts) {
585 std::deque<Reading*>& h = d->history; 641 std::deque<Reading*>& h = d->history;
642 d->last_reading_us = ts;
586 h.push_back(new Reading(d, snap, ++d->seq, ts, ++g().last_order)); 643 h.push_back(new Reading(d, snap, ++d->seq, ts, ++g().last_order));
587 while (h.size() > kHistoryCap || (h.size() > 1 && h[1]->GetTimestamp() + kHistoryUs < ts)) { 644 while (h.size() > kHistoryCap || (h.size() > 1 && h[1]->GetTimestamp() + kHistoryUs < ts)) {
588 d->evicted_order = h.front()->order(); 645 d->evicted_order = h.front()->order();
@@ -637,6 +694,13 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
637 d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5; 694 d->is_dualsense = SDL_GetGamepadType(p) == SDL_GAMEPAD_TYPE_PS5;
638 d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false); 695 d->has_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, false);
639 d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false); 696 d->has_trigger_rumble = SDL_GetBooleanProperty(props, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, false);
697 // Motion needs both sensors; SDL's orientation quaternion is left alone (no title asks for it, and a synthesised
698 // one would lie). Enabling at open: SDL delivers samples only for enabled sensors.
699 d->has_motion = SDL_GamepadHasSensor(p, SDL_SENSOR_GYRO) && SDL_GamepadHasSensor(p, SDL_SENSOR_ACCEL);
700 if (d->has_motion) {
701 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate);
702 SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate);
703 }
640 d->sent = {}; 704 d->sent = {};
641 d->sent.is_dualsense = d->is_dualsense; 705 d->sent.is_dualsense = d->is_dualsense;
642 d->sent.trigger_rumble = d->has_trigger_rumble; 706 d->sent.trigger_rumble = d->has_trigger_rumble;
@@ -662,13 +726,13 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) {
662 d->status = status; 726 d->status = status;
663 s.connected.push_back(d); 727 s.connected.push_back(d);
664 728
665 const Snapshot snap = read_pad(p); 729 const Snapshot snap = read_pad(d);
666 d->last_snap = snap; 730 d->last_snap = snap;
667 push_reading(d, snap, ts); 731 push_reading(d, snap, ts);
668 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); 732 queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0});
669 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s)\n", d->name.c_str(), d->info.vendorId, 733 std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s)\n", d->name.c_str(),
670 d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", 734 d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "",
671 d->has_trigger_rumble ? ", trigger rumble" : ""); 735 d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "");
672} 736}
673 737
674void close_pad(Device* d, uint64_t ts) { 738void close_pad(Device* d, uint64_t ts) {
@@ -984,11 +1048,15 @@ void poll_once() {
984 connected = s.connected; 1048 connected = s.connected;
985 } 1049 }
986 for (Device* d : connected) { 1050 for (Device* d : connected) {
987 const Snapshot snap = read_pad(d->pad); 1051 const Snapshot snap = read_pad(d);
988 const bool guide_changed = d->last_snap.guide != snap.guide; 1052 const bool guide_changed = d->last_snap.guide != snap.guide;
989 const bool changed = !(d->last_snap == snap); 1053 const bool changed = !(d->last_snap == snap);
990 d->last_snap = snap; 1054 d->last_snap = snap;
991 if (changed) { 1055 // A pad with sensors streams readings at ~125 Hz even when nothing else changes, so motion the title reads
1056 // between its frames is never stuck at the last button event; pads without sensors only read on change, as
1057 // before. push_reading stamps last_reading_us, so the cadence follows the actual history.
1058 const bool motion_tick = snap.has_motion && now - d->last_reading_us >= kMotionReadingUs;
1059 if (changed || motion_tick) {
992 std::lock_guard lock(s.mu); 1060 std::lock_guard lock(s.mu);
993 queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0}); 1061 queue_event({CbType::Reading, d, push_reading(d, snap, now), now, 0, 0, false, 0});
994 } 1062 }
@@ -1121,6 +1189,8 @@ HRESULT find_reading(IGameInputReading* ref, uint32_t kind, IGameInputDevice* de
1121 uint64_t horizon = 0; 1189 uint64_t horizon = 0;
1122 if (device) { 1190 if (device) {
1123 if (as_device(device)->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; 1191 if (as_device(device)->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED;
1192 if (kind != GameInputKindUnknown && !(kind & as_device(device)->info.supportedInput))
1193 return GAMEINPUT_E_READING_NOT_FOUND; // the device does not do this kind (motion on a plain pad)
1124 scope = {as_device(device)}; 1194 scope = {as_device(device)};
1125 } else { 1195 } else {
1126 horizon = r->device()->evicted_order; 1196 horizon = r->device()->evicted_order;
@@ -1165,6 +1235,8 @@ public:
1165 if (device) { 1235 if (device) {
1166 Device* d = as_device(device); 1236 Device* d = as_device(device);
1167 if (d->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED; 1237 if (d->status == GameInputDeviceNoStatus) return GAMEINPUT_E_DEVICE_DISCONNECTED;
1238 if (kind != GameInputKindUnknown && !(kind & d->info.supportedInput))
1239 return GAMEINPUT_E_READING_NOT_FOUND; // the device does not do this kind (motion on a plain pad)
1168 best = d->latest(); 1240 best = d->latest();
1169 } else { 1241 } else {
1170 for (Device* d : g().connected) // the most recent reading from any gamepad 1242 for (Device* d : g().connected) // the most recent reading from any gamepad