diff options
| author | Bora Sevim <sevimbora@gmail.com> | 2026-11-22 23:05:47 +0300 |
|---|---|---|
| committer | Bora Sevim <sevimbora@gmail.com> | 2026-11-22 23:05:47 +0300 |
| commit | 76d1add3dab43a082332579ca33f3f039746ce6b (patch) | |
| tree | 2b05cfb8571fa15ce31e0da8941533ed874218f7 /runtime/shims/gameinput.cpp | |
| parent | 364fdcbd28feb1708fd28b4727b3cc8f4a1ad1a7 (diff) | |
| parent | f847748cc76bd3777f9c070c4034eb2fc1c04e64 (diff) | |
Merge origin/main into rt-175-raw-hid
Keep RT-160's force-feedback interface and tests next to the raw HID ones.
The raw HID test fakes are renamed (FakeRawHid, raw_*) so they no longer clash
with the haptic fakes. The API table gets one IGameInputDevice row with both
feature sets; the stale duplicate IGameInputDevice and IGameInputDispatcher
rows are dropped.
Diffstat (limited to 'runtime/shims/gameinput.cpp')
| -rw-r--r-- | runtime/shims/gameinput.cpp | 673 |
1 files changed, 627 insertions, 46 deletions
diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 003efdc32..e9b32642b 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp | |||
| @@ -12,6 +12,9 @@ | |||
| 12 | // effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse | 12 | // effect (SDL_SendGamepadEffect), as set by LEONIDA_DS_TRIGGERS. That is an approximation of the Xbox impulse |
| 13 | // trigger signal, not the PS5 version's authored effects. | 13 | // trigger signal, not the PS5 version's authored effects. |
| 14 | // - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order | 14 | // - DualSense/DualShock 4 lightbar colour (LEONIDA_DS_LIGHTBAR) and the player LEDs by connection order |
| 15 | // - force-feedback motors, reported from the SDL haptic device SDL opens for the pad's joystick, and played through | ||
| 16 | // SDL_CreateHapticEffect/RunHapticEffect (IGameInputForceFeedbackEffect); haptic trigger motors, reported from the | ||
| 17 | // trigger motors the pad already has, played as an intensity through the same trigger output as SetRumbleState | ||
| 15 | // - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse | 18 | // - the keyboard pad (LEONIDA_KEYBOARD_PAD): one SDL virtual gamepad driven by the keyboard and mouse |
| 16 | // | 19 | // |
| 17 | // One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when | 20 | // One thread owns SDL: the background poll thread by default, or the caller of rt::gameinput::poll() when |
| @@ -32,6 +35,7 @@ | |||
| 32 | 35 | ||
| 33 | #include <algorithm> | 36 | #include <algorithm> |
| 34 | #include <atomic> | 37 | #include <atomic> |
| 38 | #include <chrono> | ||
| 35 | #include <cmath> | 39 | #include <cmath> |
| 36 | #include <cstdio> | 40 | #include <cstdio> |
| 37 | #include <cstdlib> | 41 | #include <cstdlib> |
| @@ -61,6 +65,9 @@ constexpr Uint32 kRumbleDurationMs = 0xFFFF; // SDL's maximum; refreshed well b | |||
| 61 | constexpr uint64_t kRumbleRefreshUs = 20'000'000; | 65 | constexpr uint64_t kRumbleRefreshUs = 20'000'000; |
| 62 | constexpr uint64_t kBatteryRefreshUs = 1'000'000; | 66 | constexpr uint64_t kBatteryRefreshUs = 1'000'000; |
| 63 | constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) | 67 | constexpr int kDsEffectSize = 47; // the DualSense effects block SDL_SendGamepadEffect forwards (SDL's DS5EffectsState_t) |
| 68 | constexpr uint32_t kForceFeedbackMotors = 1; // one per SDL haptic device: the wheel or stick it belongs to | ||
| 69 | constexpr uint32_t kHapticMotors = 2; // the left and right trigger, on a pad that backs them | ||
| 70 | constexpr uint32_t kHapticHoldMs = 60'000; // length of an effect GameInput gives no duration; re-run before it ends | ||
| 64 | constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old | 71 | constexpr uint64_t kHistoryUs = 500'000; // a reading stays in the history until the one after it is this old |
| 65 | constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate | 72 | constexpr size_t kHistoryCap = 512; // readings per pad, whatever the poll rate |
| 66 | // Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed | 73 | // Motion. SDL gives accel in m/s^2 (gravity included) and gyro in rad/s; the state the ABI defines carries signed |
| @@ -88,6 +95,37 @@ ULONG release_floor(std::atomic<ULONG>& refs) { | |||
| 88 | 95 | ||
| 89 | bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } | 96 | bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } |
| 90 | 97 | ||
| 98 | // ---- SDL haptics ------------------------------------------------------------------------------------------------ | ||
| 99 | // | ||
| 100 | // Force feedback and the trigger haptic motors go through SDL's haptic API, opened from the pad's joystick: SDL's | ||
| 101 | // gamepad API has no force feedback at all, and a wheel or stick it models as a joystick exposes one only as a haptic | ||
| 102 | // device. Every call goes through one table so gameinput_test can stand in for it, because SDL's virtual joysticks | ||
| 103 | // report no haptics and a wheel is the only other way to reach this path. | ||
| 104 | |||
| 105 | void* sdl_open_haptic(void* js) { return SDL_OpenHapticFromJoystick(static_cast<SDL_Joystick*>(js)); } | ||
| 106 | void sdl_close_haptic(void* h) { SDL_CloseHaptic(static_cast<SDL_Haptic*>(h)); } | ||
| 107 | uint32_t sdl_haptic_features(void* h) { return SDL_GetHapticFeatures(static_cast<SDL_Haptic*>(h)); } | ||
| 108 | int sdl_haptic_max_effects(void* h) { return SDL_GetMaxHapticEffects(static_cast<SDL_Haptic*>(h)); } | ||
| 109 | int sdl_haptic_create(void* h, const void* e) { | ||
| 110 | return SDL_CreateHapticEffect(static_cast<SDL_Haptic*>(h), static_cast<const SDL_HapticEffect*>(e)); | ||
| 111 | } | ||
| 112 | bool sdl_haptic_update(void* h, int id, const void* e) { | ||
| 113 | return SDL_UpdateHapticEffect(static_cast<SDL_Haptic*>(h), id, static_cast<const SDL_HapticEffect*>(e)); | ||
| 114 | } | ||
| 115 | bool sdl_haptic_run(void* h, int id, uint32_t iterations) { | ||
| 116 | return SDL_RunHapticEffect(static_cast<SDL_Haptic*>(h), id, iterations); | ||
| 117 | } | ||
| 118 | bool sdl_haptic_stop(void* h, int id) { return SDL_StopHapticEffect(static_cast<SDL_Haptic*>(h), id); } | ||
| 119 | void sdl_haptic_destroy(void* h, int id) { SDL_DestroyHapticEffect(static_cast<SDL_Haptic*>(h), id); } | ||
| 120 | bool sdl_haptic_gain(void* h, int gain) { return SDL_SetHapticGain(static_cast<SDL_Haptic*>(h), gain); } | ||
| 121 | |||
| 122 | const rt::gameinput::HapticApi kSdlHaptic{sdl_open_haptic, sdl_close_haptic, sdl_haptic_features, | ||
| 123 | sdl_haptic_max_effects, sdl_haptic_create, sdl_haptic_update, | ||
| 124 | sdl_haptic_run, sdl_haptic_stop, sdl_haptic_destroy, | ||
| 125 | sdl_haptic_gain}; | ||
| 126 | std::atomic<const rt::gameinput::HapticApi*> g_haptic_api{&kSdlHaptic}; | ||
| 127 | const rt::gameinput::HapticApi& haptics() { return *g_haptic_api.load(); } | ||
| 128 | |||
| 91 | // ---- configuration ---------------------------------------------------------------------------------------------- | 129 | // ---- configuration ---------------------------------------------------------------------------------------------- |
| 92 | 130 | ||
| 93 | std::string env(const char* name) { | 131 | std::string env(const char* name) { |
| @@ -138,6 +176,7 @@ rt::gameinput::Config read_config() { | |||
| 138 | // ---- objects ---------------------------------------------------------------------------------------------------- | 176 | // ---- objects ---------------------------------------------------------------------------------------------------- |
| 139 | 177 | ||
| 140 | class Device; | 178 | class Device; |
| 179 | class ForceFeedbackEffect; | ||
| 141 | 180 | ||
| 142 | struct Snapshot { | 181 | struct Snapshot { |
| 143 | GameInputGamepadState gamepad{}; | 182 | GameInputGamepadState gamepad{}; |
| @@ -245,6 +284,149 @@ struct Rumble { | |||
| 245 | float low = 0, high = 0, left = 0, right = 0; | 284 | float low = 0, high = 0, left = 0, right = 0; |
| 246 | }; | 285 | }; |
| 247 | 286 | ||
| 287 | // GameInput -1..1 magnitudes and 0..1 saturations against SDL's levels and saturations. | ||
| 288 | Sint16 hlevel(float v) { return static_cast<Sint16>(std::lround(std::clamp(v, -1.0f, 1.0f) * 32767.0f)); } | ||
| 289 | Uint16 hsat(float v) { return static_cast<Uint16>(std::lround(std::clamp(v, 0.0f, 1.0f) * 65535.0f)); } | ||
| 290 | uint16_t ms_from_us(uint64_t us) { return static_cast<uint16_t>(std::min<uint64_t>((us + 999) / 1000, 65535)); } | ||
| 291 | |||
| 292 | // The SDL_HAPTIC_* bit an effect kind needs, for the motor flags and the create-time check. | ||
| 293 | uint32_t kind_feature(GameInputForceFeedbackEffectKind kind) { | ||
| 294 | switch (kind) { | ||
| 295 | case GameInputForceFeedbackConstant: return SDL_HAPTIC_CONSTANT; | ||
| 296 | case GameInputForceFeedbackRamp: return SDL_HAPTIC_RAMP; | ||
| 297 | case GameInputForceFeedbackSineWave: return SDL_HAPTIC_SINE; | ||
| 298 | case GameInputForceFeedbackSquareWave: return SDL_HAPTIC_SQUARE; | ||
| 299 | case GameInputForceFeedbackTriangleWave: return SDL_HAPTIC_TRIANGLE; | ||
| 300 | case GameInputForceFeedbackSawtoothUpWave: return SDL_HAPTIC_SAWTOOTHUP; | ||
| 301 | case GameInputForceFeedbackSawtoothDownWave: return SDL_HAPTIC_SAWTOOTHDOWN; | ||
| 302 | case GameInputForceFeedbackSpring: return SDL_HAPTIC_SPRING; | ||
| 303 | case GameInputForceFeedbackFriction: return SDL_HAPTIC_FRICTION; | ||
| 304 | case GameInputForceFeedbackDamper: return SDL_HAPTIC_DAMPER; | ||
| 305 | case GameInputForceFeedbackInertia: return SDL_HAPTIC_INERTIA; | ||
| 306 | } | ||
| 307 | return 0; | ||
| 308 | } | ||
| 309 | |||
| 310 | bool valid_kind(GameInputForceFeedbackEffectKind kind) { | ||
| 311 | return kind >= GameInputForceFeedbackConstant && kind <= GameInputForceFeedbackInertia; | ||
| 312 | } | ||
| 313 | |||
| 314 | // An all-zero envelope is how a title that only sets a magnitude leaves it: that means no envelope, not silence. | ||
| 315 | bool envelope_used(const GameInputForceFeedbackEnvelope& e) { | ||
| 316 | return e.attackDuration || e.sustainDuration || e.releaseDuration || e.attackGain != 0.0f || | ||
| 317 | e.sustainGain != 0.0f || e.releaseGain != 0.0f || e.playCount || e.repeatDelay; | ||
| 318 | } | ||
| 319 | |||
| 320 | uint32_t play_count(const GameInputForceFeedbackParams& p) { | ||
| 321 | return p.kind <= GameInputForceFeedbackSawtoothDownWave ? p.data.constant.envelope.playCount : 0; | ||
| 322 | } | ||
| 323 | |||
| 324 | // One GameInput effect as SDL's template. GameInput's eleven kinds are SDL's eleven force-feedback effects, so the | ||
| 325 | // kind picks the SDL type and the fields are magnitudes; conditions have no envelope in GameInput either. Returns | ||
| 326 | // false for a kind the shim does not map. `endless` says the effect has no duration of its own (GameInput left the | ||
| 327 | // envelope empty), which is what the poll thread re-runs before the SDL length runs out. | ||
| 328 | bool build_effect(const GameInputForceFeedbackParams& p, float gain, bool* endless, uint32_t* length_ms, | ||
| 329 | SDL_HapticEffect* out) { | ||
| 330 | std::memset(out, 0, sizeof *out); | ||
| 331 | if (!valid_kind(p.kind)) return false; | ||
| 332 | const bool envelope_kind = p.kind <= GameInputForceFeedbackSawtoothDownWave; | ||
| 333 | const GameInputForceFeedbackEnvelope env = envelope_kind ? p.data.constant.envelope : GameInputForceFeedbackEnvelope{}; | ||
| 334 | const bool used = envelope_kind && envelope_used(env); | ||
| 335 | const float level = gain * (used ? env.sustainGain : 1.0f); // GameInput's sustainGain is the effect's level | ||
| 336 | const uint64_t total_us = used ? env.attackDuration + env.sustainDuration + env.releaseDuration : 0; | ||
| 337 | *endless = total_us == 0; | ||
| 338 | *length_ms = total_us == 0 ? kHapticHoldMs | ||
| 339 | : static_cast<uint32_t>(std::clamp<uint64_t>((total_us + 999) / 1000, 1, 86'400'000)); | ||
| 340 | // The envelope's attack and release, when the title gave one. SDL only uses the envelope when attack_length or | ||
| 341 | // fade_level is set, so a zero-gain envelope is left alone rather than muting the effect. | ||
| 342 | auto envelope = [&](SDL_HapticConstant& e) { | ||
| 343 | if (!used || (!env.attackDuration && !env.releaseDuration)) return; | ||
| 344 | e.attack_length = ms_from_us(env.attackDuration); | ||
| 345 | e.attack_level = hsat(env.attackGain); | ||
| 346 | e.fade_length = ms_from_us(env.releaseDuration); | ||
| 347 | e.fade_level = hsat(env.releaseGain); | ||
| 348 | }; | ||
| 349 | // Force along +X: the axis a wheel's or a stick's motor acts on, which is the one the motor reports (LinearX). | ||
| 350 | auto direction = [](SDL_HapticDirection& d) { | ||
| 351 | d.type = SDL_HAPTIC_CARTESIAN; | ||
| 352 | d.dir[0] = 1; | ||
| 353 | }; | ||
| 354 | switch (p.kind) { | ||
| 355 | case GameInputForceFeedbackConstant: { | ||
| 356 | SDL_HapticConstant& e = out->constant; | ||
| 357 | e.type = SDL_HAPTIC_CONSTANT; | ||
| 358 | direction(e.direction); | ||
| 359 | e.length = *length_ms; | ||
| 360 | e.level = hlevel(p.data.constant.magnitude.linearX * level); | ||
| 361 | envelope(e); | ||
| 362 | break; | ||
| 363 | } | ||
| 364 | case GameInputForceFeedbackRamp: { | ||
| 365 | SDL_HapticRamp& e = out->ramp; | ||
| 366 | e.type = SDL_HAPTIC_RAMP; | ||
| 367 | direction(e.direction); | ||
| 368 | e.length = *length_ms; | ||
| 369 | e.start = hlevel(p.data.ramp.startMagnitude.linearX * level); | ||
| 370 | e.end = hlevel(p.data.ramp.endMagnitude.linearX * level); | ||
| 371 | if (used) { | ||
| 372 | e.attack_length = ms_from_us(env.attackDuration); | ||
| 373 | e.attack_level = hsat(env.attackGain); | ||
| 374 | e.fade_length = ms_from_us(env.releaseDuration); | ||
| 375 | e.fade_level = hsat(env.releaseGain); | ||
| 376 | } | ||
| 377 | break; | ||
| 378 | } | ||
| 379 | case GameInputForceFeedbackSineWave: | ||
| 380 | case GameInputForceFeedbackSquareWave: | ||
| 381 | case GameInputForceFeedbackTriangleWave: | ||
| 382 | case GameInputForceFeedbackSawtoothUpWave: | ||
| 383 | case GameInputForceFeedbackSawtoothDownWave: { | ||
| 384 | SDL_HapticPeriodic& e = out->periodic; | ||
| 385 | e.type = p.kind == GameInputForceFeedbackSineWave ? SDL_HAPTIC_SINE | ||
| 386 | : p.kind == GameInputForceFeedbackSquareWave ? SDL_HAPTIC_SQUARE | ||
| 387 | : p.kind == GameInputForceFeedbackTriangleWave ? SDL_HAPTIC_TRIANGLE | ||
| 388 | : p.kind == GameInputForceFeedbackSawtoothUpWave ? SDL_HAPTIC_SAWTOOTHUP | ||
| 389 | : SDL_HAPTIC_SAWTOOTHDOWN; | ||
| 390 | direction(e.direction); | ||
| 391 | e.length = *length_ms; | ||
| 392 | const GameInputForceFeedbackPeriodicParams& pp = p.data.sineWave; | ||
| 393 | // GameInput gives the wave's frequency in Hz and its phase in degrees; SDL wants a period in ms and a | ||
| 394 | // phase in hundredths of a degree. | ||
| 395 | e.period = pp.frequency > 0.0f ? static_cast<Uint16>(std::clamp(std::lround(1000.0f / pp.frequency), 1L, 65535L)) : 100; | ||
| 396 | e.magnitude = hlevel(pp.magnitude.linearX * level); | ||
| 397 | e.offset = hlevel(pp.bias * level); | ||
| 398 | e.phase = static_cast<Uint16>(std::clamp(std::lround(pp.phase * 100.0f), 0L, 35999L)); | ||
| 399 | if (used) { | ||
| 400 | e.attack_length = ms_from_us(env.attackDuration); | ||
| 401 | e.attack_level = hsat(env.attackGain); | ||
| 402 | e.fade_length = ms_from_us(env.releaseDuration); | ||
| 403 | e.fade_level = hsat(env.releaseGain); | ||
| 404 | } | ||
| 405 | break; | ||
| 406 | } | ||
| 407 | default: { // spring, friction, damper, inertia | ||
| 408 | SDL_HapticCondition& e = out->condition; | ||
| 409 | e.type = p.kind == GameInputForceFeedbackSpring ? SDL_HAPTIC_SPRING | ||
| 410 | : p.kind == GameInputForceFeedbackFriction ? SDL_HAPTIC_FRICTION | ||
| 411 | : p.kind == GameInputForceFeedbackDamper ? SDL_HAPTIC_DAMPER | ||
| 412 | : SDL_HAPTIC_INERTIA; | ||
| 413 | e.length = *length_ms; | ||
| 414 | const GameInputForceFeedbackConditionParams& cp = p.data.spring; | ||
| 415 | const float center[3] = {cp.magnitude.linearX, cp.magnitude.linearY, cp.magnitude.linearZ}; | ||
| 416 | for (int a = 0; a < 3; ++a) { | ||
| 417 | e.right_sat[a] = hsat(cp.maxPositiveMagnitude); | ||
| 418 | e.left_sat[a] = hsat(cp.maxNegativeMagnitude); | ||
| 419 | e.right_coeff[a] = hlevel(cp.positiveCoefficient * level); | ||
| 420 | e.left_coeff[a] = hlevel(-cp.negativeCoefficient * level); | ||
| 421 | e.deadband[a] = hsat(cp.deadZone); | ||
| 422 | e.center[a] = hlevel(center[a]); | ||
| 423 | } | ||
| 424 | break; | ||
| 425 | } | ||
| 426 | } | ||
| 427 | return true; | ||
| 428 | } | ||
| 429 | |||
| 248 | class Device final : public IGameInputDevice { | 430 | class Device final : public IGameInputDevice { |
| 249 | public: | 431 | public: |
| 250 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { | 432 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { |
| @@ -265,13 +447,10 @@ public: | |||
| 265 | const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; } | 447 | const GameInputDeviceInfo* STDMETHODCALLTYPE GetDeviceInfo() override { return &info; } |
| 266 | uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); } | 448 | uint32_t STDMETHODCALLTYPE GetDeviceStatus() override { return status.load(); } |
| 267 | void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override; | 449 | void STDMETHODCALLTYPE GetBatteryState(GameInputBatteryState* state) override; |
| 268 | HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t, const void*, void** effect) override { | 450 | HRESULT STDMETHODCALLTYPE CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) override; |
| 269 | if (effect) *effect = nullptr; | 451 | bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) override; |
| 270 | return E_INVALIDARG; // forceFeedbackMotorCount is 0 | 452 | void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) override; |
| 271 | } | 453 | HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t motorIndex, const void* params) override; |
| 272 | bool STDMETHODCALLTYPE IsForceFeedbackMotorPoweredOn(uint32_t) override { return false; } | ||
| 273 | void STDMETHODCALLTYPE SetForceFeedbackMotorGain(uint32_t, float) override {} | ||
| 274 | HRESULT STDMETHODCALLTYPE SetHapticMotorState(uint32_t, const void*) override { return E_INVALIDARG; } | ||
| 275 | void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override; | 454 | void STDMETHODCALLTYPE SetRumbleState(const GameInputRumbleParams* params) override; |
| 276 | void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} | 455 | void STDMETHODCALLTYPE SetInputSynchronizationState(bool) override {} |
| 277 | void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} | 456 | void STDMETHODCALLTYPE SendInputSynchronizationHint() override {} |
| @@ -301,12 +480,20 @@ public: | |||
| 301 | GameInputGamepadInfo gamepad_info{}; | 480 | GameInputGamepadInfo gamepad_info{}; |
| 302 | GameInputUiNavigationInfo ui_info{}; | 481 | GameInputUiNavigationInfo ui_info{}; |
| 303 | GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it | 482 | GameInputMotionInfo motion_info{}; // filled only when the pad has sensors; info.motionInfo points at it |
| 483 | GameInputForceFeedbackMotorInfo ff_motor_info{}; // filled when SDL opened the pad as a haptic device | ||
| 484 | GameInputHapticFeedbackMotorInfo haptic_motor_info[kHapticMotors]{}; // the trigger motors, when the pad has them | ||
| 485 | GameInputHapticWaveformInfo haptic_waveform_info[kHapticMotors]{}; // one waveform each, an intensity | ||
| 304 | std::atomic<uint32_t> status{GameInputDeviceNoStatus}; | 486 | std::atomic<uint32_t> status{GameInputDeviceNoStatus}; |
| 305 | std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading | 487 | std::deque<Reading*> history; // one reference each, oldest first; the newest is the current reading |
| 306 | uint64_t evicted_order = 0; // order of the newest reading dropped from history | 488 | uint64_t evicted_order = 0; // order of the newest reading dropped from history |
| 307 | Reading* latest() const { return history.empty() ? nullptr : history.back(); } | 489 | Reading* latest() const { return history.empty() ? nullptr : history.back(); } |
| 308 | uint64_t seq = 0; | 490 | uint64_t seq = 0; |
| 309 | Rumble wanted; | 491 | Rumble wanted; |
| 492 | float motor_gain = 1.0f; // SetForceFeedbackMotorGain, 0..1 | ||
| 493 | std::vector<ForceFeedbackEffect*> effects; // every live effect, so the poll thread can drive them | ||
| 494 | std::vector<int> retired; // SDL effect ids whose object is gone: destroyed on the poll thread | ||
| 495 | float haptic_intensity[kHapticMotors] = {}; // SetHapticMotorState, 0..1 | ||
| 496 | uint64_t haptic_until[kHapticMotors] = {}; // when the request ends, 0 for "until changed" | ||
| 310 | GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown}; | 497 | GameInputBatteryState battery{0, 0, 0, 0, GameInputBatteryUnknown}; |
| 311 | AppLocalDeviceId base_id{}; // id_bytes of the identity alone: twins share it, info.deviceId tells them apart | 498 | AppLocalDeviceId base_id{}; // id_bytes of the identity alone: twins share it, info.deviceId tells them apart |
| 312 | 499 | ||
| @@ -315,6 +502,11 @@ public: | |||
| 315 | SDL_JoystickID id = 0; | 502 | SDL_JoystickID id = 0; |
| 316 | int player = -1; | 503 | int player = -1; |
| 317 | bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false; | 504 | bool is_dualsense = false, has_rumble = false, has_trigger_rumble = false, has_motion = false; |
| 505 | bool has_trigger_output = false; // the pad backs trigger motors: rumble, DualSense effects or haptic motors | ||
| 506 | void* haptic = nullptr; // SDL_Haptic behind the joystick, when SDL has one for this pad | ||
| 507 | uint32_t ff_features = 0; // the SDL_HAPTIC_* bits it reports: which effect kinds it can play | ||
| 508 | int sent_gain = -1; // device gain 0..100 last sent, so a steady gain costs one call | ||
| 509 | uint32_t haptic_motors = 0; // trigger haptic motors the pad reports (0 or 2) | ||
| 318 | rt::gameinput::OutputState sent{}; | 510 | rt::gameinput::OutputState sent{}; |
| 319 | Snapshot last_snap{}; // what the latest reading holds | 511 | Snapshot last_snap{}; // what the latest reading holds |
| 320 | uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors | 512 | uint64_t last_reading_us = 0; // for the motion cadence: readings stream at ~125 Hz on pads with sensors |
| @@ -545,6 +737,50 @@ struct Event { | |||
| 545 | GameInputCallbackToken only; // enumeration: deliver to this callback only | 737 | GameInputCallbackToken only; // enumeration: deliver to this callback only |
| 546 | }; | 738 | }; |
| 547 | 739 | ||
| 740 | // One effect a title created, on the device it belongs to. The object and its parameters belong to the title; SDL's | ||
| 741 | // effect is created, run and destroyed on the poll thread, so a title call only writes its state and bumps `version_`, | ||
| 742 | // which the poll thread compares before it touches SDL. A new effect is Running: CreateForceFeedbackEffect already | ||
| 743 | // carried the parameters, and the documented use (create once, SetParams per frame) never reaches SetState. | ||
| 744 | class ForceFeedbackEffect final : public IGameInputForceFeedbackEffect { | ||
| 745 | public: | ||
| 746 | ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params); | ||
| 747 | ~ForceFeedbackEffect(); | ||
| 748 | |||
| 749 | HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override; | ||
| 750 | ULONG STDMETHODCALLTYPE AddRef() override; | ||
| 751 | ULONG STDMETHODCALLTYPE Release() override; | ||
| 752 | void STDMETHODCALLTYPE GetDevice(IGameInputDevice** device) override; | ||
| 753 | uint32_t STDMETHODCALLTYPE GetMotorIndex() override; | ||
| 754 | float STDMETHODCALLTYPE GetGain() override; | ||
| 755 | void STDMETHODCALLTYPE SetGain(float gain) override; | ||
| 756 | void STDMETHODCALLTYPE GetParams(GameInputForceFeedbackParams* params) override; | ||
| 757 | bool STDMETHODCALLTYPE SetParams(const GameInputForceFeedbackParams* params) override; | ||
| 758 | GameInputFeedbackEffectState STDMETHODCALLTYPE GetState() override; | ||
| 759 | void STDMETHODCALLTYPE SetState(GameInputFeedbackEffectState state) override; | ||
| 760 | |||
| 761 | // Poll thread: make SDL match the effect's parameters, gain and state. `muted` says every output is off | ||
| 762 | // (LEONIDA_RUMBLE=0); the motor's master gain is SDL's device gain, set once by apply_effects. | ||
| 763 | void sync(Device* device, uint64_t now, bool muted); | ||
| 764 | // Poll thread, on unplug: the SDL device went with the pad, so forget its effect id without touching SDL. | ||
| 765 | void orphan(); | ||
| 766 | |||
| 767 | private: | ||
| 768 | std::atomic<ULONG> refs_{1}; | ||
| 769 | Device* device_; | ||
| 770 | uint32_t motor_; | ||
| 771 | // Written by title calls under g().mu and read by the poll thread. | ||
| 772 | GameInputForceFeedbackParams params_; | ||
| 773 | float gain_ = 1.0f; | ||
| 774 | GameInputFeedbackEffectState state_ = GameInputFeedbackRunning; | ||
| 775 | uint64_t version_ = 1; | ||
| 776 | // Poll thread only. | ||
| 777 | uint64_t applied_ = 0; // the version SDL has | ||
| 778 | int sdl_effect_ = -1; | ||
| 779 | bool sdl_running_ = false; | ||
| 780 | bool endless_ = true; // GameInput gave no duration: re-run before the SDL length runs out | ||
| 781 | uint64_t run_at_ = 0, run_for_ = 0; | ||
| 782 | }; | ||
| 783 | |||
| 548 | class Dispatcher; | 784 | class Dispatcher; |
| 549 | 785 | ||
| 550 | struct State { | 786 | struct State { |
| @@ -609,6 +845,28 @@ void call(const Callback& c, const Event& e) { | |||
| 609 | } | 845 | } |
| 610 | } | 846 | } |
| 611 | 847 | ||
| 848 | // Runs one queued event's callbacks on the calling thread, without holding the state lock. | ||
| 849 | void deliver_event(const Event& e) { | ||
| 850 | State& s = g(); | ||
| 851 | std::vector<Callback> targets; | ||
| 852 | { | ||
| 853 | std::lock_guard lock(s.mu); | ||
| 854 | for (const Callback& c : s.callbacks) | ||
| 855 | if (matches(c, e)) targets.push_back(c); | ||
| 856 | } | ||
| 857 | for (const Callback& c : targets) { | ||
| 858 | bool still = false; | ||
| 859 | { | ||
| 860 | std::lock_guard lock(s.mu); | ||
| 861 | for (const Callback& now : s.callbacks) | ||
| 862 | if (now.token == c.token) still = now.active; | ||
| 863 | } | ||
| 864 | if (still) call(c, e); | ||
| 865 | } | ||
| 866 | if (e.device) e.device->Release(); | ||
| 867 | if (e.reading) e.reading->Release(); | ||
| 868 | } | ||
| 869 | |||
| 612 | // Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived | 870 | // Runs queued callbacks on the calling thread, without holding the state lock. Returns whether more events arrived |
| 613 | // meanwhile. | 871 | // meanwhile. |
| 614 | bool deliver() { | 872 | bool deliver() { |
| @@ -619,30 +877,41 @@ bool deliver() { | |||
| 619 | std::lock_guard lock(s.mu); | 877 | std::lock_guard lock(s.mu); |
| 620 | events.swap(s.queue); | 878 | events.swap(s.queue); |
| 621 | } | 879 | } |
| 622 | const DWORD self = GetCurrentThreadId(); | 880 | s.delivering_thread = GetCurrentThreadId(); |
| 623 | s.delivering_thread = self; | 881 | for (const Event& e : events) deliver_event(e); |
| 624 | for (const Event& e : events) { | 882 | s.delivering_thread = 0; |
| 625 | std::vector<Callback> targets; | 883 | std::lock_guard lock(s.mu); |
| 884 | return !s.queue.empty(); | ||
| 885 | } | ||
| 886 | |||
| 887 | // IGameInputDispatcher::Dispatch: runs queued events oldest first, at least one even with a quota of 0, and takes no | ||
| 888 | // further event once quota_us microseconds have passed (an event already started runs to the end, so the quota is a | ||
| 889 | // target, as on Windows). While events remain the wait handle is signalled again, so a title that waits on it before | ||
| 890 | // each call comes back for the rest. Returns whether events remain. | ||
| 891 | bool deliver_within(uint64_t quota_us) { | ||
| 892 | State& s = g(); | ||
| 893 | std::lock_guard dl(s.deliver_mu); | ||
| 894 | const auto start = std::chrono::steady_clock::now(); | ||
| 895 | s.delivering_thread = GetCurrentThreadId(); | ||
| 896 | for (bool first = true;; first = false) { | ||
| 897 | if (!first) { | ||
| 898 | const auto spent = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - start); | ||
| 899 | if (static_cast<uint64_t>(spent.count()) >= quota_us) break; | ||
| 900 | } | ||
| 901 | Event e; | ||
| 626 | { | 902 | { |
| 627 | std::lock_guard lock(s.mu); | 903 | std::lock_guard lock(s.mu); |
| 628 | for (const Callback& c : s.callbacks) | 904 | if (s.queue.empty()) break; |
| 629 | if (matches(c, e)) targets.push_back(c); | 905 | e = s.queue.front(); |
| 906 | s.queue.erase(s.queue.begin()); | ||
| 630 | } | 907 | } |
| 631 | for (const Callback& c : targets) { | 908 | deliver_event(e); |
| 632 | bool still = false; | ||
| 633 | { | ||
| 634 | std::lock_guard lock(s.mu); | ||
| 635 | for (const Callback& now : s.callbacks) | ||
| 636 | if (now.token == c.token) still = now.active; | ||
| 637 | } | ||
| 638 | if (still) call(c, e); | ||
| 639 | } | ||
| 640 | if (e.device) e.device->Release(); | ||
| 641 | if (e.reading) e.reading->Release(); | ||
| 642 | } | 909 | } |
| 643 | s.delivering_thread = 0; | 910 | s.delivering_thread = 0; |
| 644 | std::lock_guard lock(s.mu); | 911 | std::lock_guard lock(s.mu); |
| 645 | return !s.queue.empty(); | 912 | const bool remaining = !s.queue.empty(); |
| 913 | if (remaining && s.wait_event) SetEvent(s.wait_event); | ||
| 914 | return remaining; | ||
| 646 | } | 915 | } |
| 647 | 916 | ||
| 648 | // ---- SDL backend (poll thread only) ----------------------------------------------------------------------------- | 917 | // ---- SDL backend (poll thread only) ----------------------------------------------------------------------------- |
| @@ -781,8 +1050,7 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) { | |||
| 781 | // as the per-device one, so only pads with sensors answer a motion query. | 1050 | // as the per-device one, so only pads with sensors answer a motion query. |
| 782 | i.supportedInput = kBaseKinds; | 1051 | i.supportedInput = kBaseKinds; |
| 783 | if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; | 1052 | if (d->has_rumble) i.supportedRumbleMotors |= GameInputRumbleLowFrequency | GameInputRumbleHighFrequency; |
| 784 | if (d->has_trigger_rumble || (d->is_dualsense && g().config.ds_triggers != rt::gameinput::DsTriggerMode::Off)) | 1053 | if (d->has_trigger_output) i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger; |
| 785 | i.supportedRumbleMotors |= GameInputRumbleLeftTrigger | GameInputRumbleRightTrigger; | ||
| 786 | if (d->has_motion) { | 1054 | if (d->has_motion) { |
| 787 | i.supportedInput |= GameInputKindMotion; | 1055 | i.supportedInput |= GameInputKindMotion; |
| 788 | // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has | 1056 | // The maxima GetMotionState's fractions divide by. The magnetometer is not available: SDL's gamepad API has |
| @@ -790,6 +1058,17 @@ void fill_info(Device* d, SDL_Gamepad* p, const AppLocalDeviceId& id) { | |||
| 790 | d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f}; | 1058 | d->motion_info = {kMaxAcceleration, kMaxAngularVelocity, 0.0f}; |
| 791 | i.motionInfo = &d->motion_info; | 1059 | i.motionInfo = &d->motion_info; |
| 792 | } | 1060 | } |
| 1061 | // The motors this pad can back. Force feedback is whatever SDL opened a haptic device for with effect kinds of its | ||
| 1062 | // own; the haptic motors are the trigger motors the pad already has for rumble, which the shim can drive as an | ||
| 1063 | // intensity. A pad with neither keeps the old answers: no motors at all. | ||
| 1064 | if (d->haptic) { | ||
| 1065 | i.forceFeedbackMotorCount = kForceFeedbackMotors; | ||
| 1066 | i.forceFeedbackMotorInfo = &d->ff_motor_info; | ||
| 1067 | } | ||
| 1068 | if (d->haptic_motors) { | ||
| 1069 | i.hapticFeedbackMotorCount = d->haptic_motors; | ||
| 1070 | i.hapticFeedbackMotorInfo = d->haptic_motor_info; | ||
| 1071 | } | ||
| 793 | i.controllerAxisCount = kAxisCount; | 1072 | i.controllerAxisCount = kAxisCount; |
| 794 | i.controllerButtonCount = kButtonCount; | 1073 | i.controllerButtonCount = kButtonCount; |
| 795 | for (uint32_t a = 0; a < kAxisCount; ++a) { | 1074 | for (uint32_t a = 0; a < kAxisCount; ++a) { |
| @@ -973,9 +1252,60 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { | |||
| 973 | SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate); | 1252 | SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_GYRO, kMotionSensorRate); |
| 974 | SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate); | 1253 | SDL_SetGamepadSensorEnabled(p, SDL_SENSOR_ACCEL, kMotionSensorRate); |
| 975 | } | 1254 | } |
| 1255 | d->has_trigger_output = d->has_trigger_rumble || | ||
| 1256 | (d->is_dualsense && s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off); | ||
| 1257 | // Force feedback: SDL opens a wheel or a stick as a joystick with a haptic device behind it and never through the | ||
| 1258 | // gamepad API, so it is opened from the joystick and closed with the pad. Only what the device really reports is | ||
| 1259 | // passed on: no haptic device, no motor, and an effect kind SDL does not list is not offered to a title. | ||
| 1260 | d->haptic = haptics().open_joystick(SDL_GetGamepadJoystick(p)); | ||
| 1261 | d->ff_features = 0; | ||
| 1262 | d->ff_motor_info = {}; | ||
| 1263 | d->sent_gain = -1; | ||
| 1264 | if (d->haptic) { | ||
| 1265 | const uint32_t features = haptics().features(d->haptic); | ||
| 1266 | if (features) { | ||
| 1267 | GameInputForceFeedbackMotorInfo& m = d->ff_motor_info; | ||
| 1268 | d->ff_features = features; | ||
| 1269 | m.supportedAxes = GameInputFeedbackAxisLinearX; // the axis a wheel's or a stick's motor acts on | ||
| 1270 | m.location = GameInputLocationChassis; | ||
| 1271 | m.locationId = 0; | ||
| 1272 | m.maxSimultaneousEffects = static_cast<uint32_t>(std::max(1, haptics().max_effects(d->haptic))); | ||
| 1273 | m.isConstantEffectSupported = (features & SDL_HAPTIC_CONSTANT) != 0; | ||
| 1274 | m.isRampEffectSupported = (features & SDL_HAPTIC_RAMP) != 0; | ||
| 1275 | m.isSineWaveEffectSupported = (features & SDL_HAPTIC_SINE) != 0; | ||
| 1276 | m.isSquareWaveEffectSupported = (features & SDL_HAPTIC_SQUARE) != 0; | ||
| 1277 | m.isTriangleWaveEffectSupported = (features & SDL_HAPTIC_TRIANGLE) != 0; | ||
| 1278 | m.isSawtoothUpWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHUP) != 0; | ||
| 1279 | m.isSawtoothDownWaveEffectSupported = (features & SDL_HAPTIC_SAWTOOTHDOWN) != 0; | ||
| 1280 | m.isSpringEffectSupported = (features & SDL_HAPTIC_SPRING) != 0; | ||
| 1281 | m.isFrictionEffectSupported = (features & SDL_HAPTIC_FRICTION) != 0; | ||
| 1282 | m.isDamperEffectSupported = (features & SDL_HAPTIC_DAMPER) != 0; | ||
| 1283 | m.isInertiaEffectSupported = (features & SDL_HAPTIC_INERTIA) != 0; | ||
| 1284 | } else { | ||
| 1285 | haptics().close(d->haptic); | ||
| 1286 | d->haptic = nullptr; | ||
| 1287 | } | ||
| 1288 | } | ||
| 1289 | // Haptic motors: the trigger motors, one waveform each. The waveform identifier is this shim's choice, an | ||
| 1290 | // intensity (HID physical-interface usage 0x0F/0x58), because an intensity is the one thing SDL lets it send. | ||
| 1291 | d->haptic_motors = 0; | ||
| 1292 | if (d->has_trigger_output) { | ||
| 1293 | for (uint32_t m = 0; m < kHapticMotors; ++m) { | ||
| 1294 | d->haptic_waveform_info[m] = {{0x0F, 0x58}, true, true, true, false, 0}; | ||
| 1295 | d->haptic_motor_info[m] = {}; | ||
| 1296 | d->haptic_motor_info[m].mappedRumbleMotors = m ? GameInputRumbleRightTrigger : GameInputRumbleLeftTrigger; | ||
| 1297 | d->haptic_motor_info[m].location = GameInputLocationChassis; | ||
| 1298 | d->haptic_motor_info[m].locationId = m; | ||
| 1299 | d->haptic_motor_info[m].waveformCount = 1; | ||
| 1300 | d->haptic_motor_info[m].waveformInfo = &d->haptic_waveform_info[m]; | ||
| 1301 | } | ||
| 1302 | d->haptic_motors = kHapticMotors; | ||
| 1303 | } | ||
| 976 | d->sent = {}; | 1304 | d->sent = {}; |
| 977 | d->sent.is_dualsense = d->is_dualsense; | 1305 | d->sent.is_dualsense = d->is_dualsense; |
| 978 | d->sent.trigger_rumble = d->has_trigger_rumble; | 1306 | d->sent.trigger_rumble = d->has_trigger_rumble; |
| 1307 | d->sent.force_feedback = d->haptic != nullptr; | ||
| 1308 | d->sent.haptic_motors = d->haptic_motors; | ||
| 979 | d->ds_sent_once = false; | 1309 | d->ds_sent_once = false; |
| 980 | d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0; | 1310 | d->motors_sent_at = d->triggers_sent_at = d->battery_at = 0; |
| 981 | d->wanted = {}; | 1311 | d->wanted = {}; |
| @@ -1004,9 +1334,10 @@ void open_pad(SDL_JoystickID jid, uint64_t ts) { | |||
| 1004 | d->last_snap = snap; | 1334 | d->last_snap = snap; |
| 1005 | push_reading(d, snap, ts); | 1335 | push_reading(d, snap, ts); |
| 1006 | queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); | 1336 | queue_event({CbType::Device, d, nullptr, ts, status, GameInputDeviceNoStatus, false, 0}); |
| 1007 | std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s)\n", d->name.c_str(), | 1337 | std::fprintf(stderr, "[rt] gameinput: connected %s (%04x:%04x, player %d%s%s%s%s)\n", d->name.c_str(), |
| 1008 | d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", | 1338 | d->info.vendorId, d->info.productId, player + 1, d->is_dualsense ? ", DualSense trigger effects" : "", |
| 1009 | d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : ""); | 1339 | d->has_trigger_rumble ? ", trigger rumble" : "", d->has_motion ? ", gyro" : "", |
| 1340 | d->haptic ? ", force feedback" : ""); | ||
| 1010 | } | 1341 | } |
| 1011 | 1342 | ||
| 1012 | void close_pad(Device* d, uint64_t ts) { | 1343 | void close_pad(Device* d, uint64_t ts) { |
| @@ -1017,6 +1348,19 @@ void close_pad(Device* d, uint64_t ts) { | |||
| 1017 | close_raw(d); | 1348 | close_raw(d); |
| 1018 | d->pad = nullptr; | 1349 | d->pad = nullptr; |
| 1019 | d->player = -1; | 1350 | d->player = -1; |
| 1351 | // The haptic device belongs to the joystick, which goes with the gamepad. Effects a title still holds stay alive | ||
| 1352 | // and pick up again when the pad comes back. | ||
| 1353 | if (d->haptic) { | ||
| 1354 | haptics().close(d->haptic); | ||
| 1355 | d->haptic = nullptr; | ||
| 1356 | } | ||
| 1357 | d->retired.clear(); | ||
| 1358 | d->ff_features = 0; | ||
| 1359 | d->ff_motor_info = {}; | ||
| 1360 | d->sent_gain = -1; | ||
| 1361 | d->haptic_motors = 0; | ||
| 1362 | for (ForceFeedbackEffect* e : d->effects) e->orphan(); | ||
| 1363 | for (uint32_t m = 0; m < kHapticMotors; ++m) d->haptic_intensity[m] = 0, d->haptic_until[m] = 0; | ||
| 1020 | if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session | 1364 | if (!d->history.empty()) d->evicted_order = d->history.back()->order(); // the history ends with the session |
| 1021 | for (Reading* r : d->history) r->Release(); | 1365 | for (Reading* r : d->history) r->Release(); |
| 1022 | d->history.clear(); | 1366 | d->history.clear(); |
| @@ -1043,14 +1387,55 @@ void ds_effect(float strength, uint8_t out[11]) { | |||
| 1043 | } | 1387 | } |
| 1044 | } | 1388 | } |
| 1045 | 1389 | ||
| 1390 | // The force-feedback effects and the device gain, on the poll thread: SDL's effects are created, updated, run and | ||
| 1391 | // destroyed here and nowhere else, so a title call costs a lock and a copy. | ||
| 1392 | void apply_effects(Device* d, uint64_t now) { | ||
| 1393 | State& s = g(); | ||
| 1394 | std::vector<ForceFeedbackEffect*> live; | ||
| 1395 | std::vector<int> retire; | ||
| 1396 | float motor_gain; | ||
| 1397 | bool muted; | ||
| 1398 | { | ||
| 1399 | std::lock_guard lock(s.mu); | ||
| 1400 | live.reserve(d->effects.size()); | ||
| 1401 | for (ForceFeedbackEffect* e : d->effects) { // referenced: the title may release one while this runs | ||
| 1402 | e->AddRef(); | ||
| 1403 | live.push_back(e); | ||
| 1404 | } | ||
| 1405 | retire.swap(d->retired); | ||
| 1406 | motor_gain = d->motor_gain; | ||
| 1407 | muted = !s.config.rumble; | ||
| 1408 | } | ||
| 1409 | if (d->haptic) { | ||
| 1410 | for (int id : retire) haptics().destroy_effect(d->haptic, id); | ||
| 1411 | const int gain = static_cast<int>(std::lround(std::clamp(motor_gain, 0.0f, 1.0f) * 100.0f)); | ||
| 1412 | if (gain != d->sent_gain) { | ||
| 1413 | haptics().set_gain(d->haptic, gain); | ||
| 1414 | d->sent_gain = gain; | ||
| 1415 | } | ||
| 1416 | } | ||
| 1417 | for (ForceFeedbackEffect* e : live) { | ||
| 1418 | e->sync(d, now, muted); | ||
| 1419 | e->Release(); | ||
| 1420 | } | ||
| 1421 | } | ||
| 1422 | |||
| 1046 | void apply_output(Device* d, uint64_t now) { | 1423 | void apply_output(Device* d, uint64_t now) { |
| 1047 | State& s = g(); | 1424 | State& s = g(); |
| 1048 | Rumble want; | 1425 | Rumble want; |
| 1426 | float haptic[kHapticMotors] = {}; | ||
| 1049 | { | 1427 | { |
| 1050 | std::lock_guard lock(s.mu); | 1428 | std::lock_guard lock(s.mu); |
| 1051 | want = d->wanted; | 1429 | want = d->wanted; |
| 1052 | } | 1430 | for (uint32_t m = 0; m < d->haptic_motors; ++m) |
| 1053 | if (!s.config.rumble) want = {}; | 1431 | if (!d->haptic_until[m] || now < d->haptic_until[m]) haptic[m] = d->haptic_intensity[m]; |
| 1432 | } | ||
| 1433 | const bool muted = !s.config.rumble; | ||
| 1434 | if (muted) want = {}; | ||
| 1435 | // The haptic motors sit on the trigger motors, so their intensity and SetRumbleState's trigger level go out on one | ||
| 1436 | // output: the stronger of the two wins, and a request that has run out is dropped here. | ||
| 1437 | want.left = std::max(want.left, muted ? 0.0f : haptic[0]); | ||
| 1438 | want.right = std::max(want.right, muted ? 0.0f : haptic[1]); | ||
| 1054 | rt::gameinput::OutputState& o = d->sent; | 1439 | rt::gameinput::OutputState& o = d->sent; |
| 1055 | 1440 | ||
| 1056 | if (d->has_rumble) { | 1441 | if (d->has_rumble) { |
| @@ -1064,19 +1449,21 @@ void apply_output(Device* d, uint64_t now) { | |||
| 1064 | } | 1449 | } |
| 1065 | } | 1450 | } |
| 1066 | if (d->is_dualsense) { | 1451 | if (d->is_dualsense) { |
| 1067 | if (s.config.ds_triggers == rt::gameinput::DsTriggerMode::Off) return; // leave the triggers alone | 1452 | // LEONIDA_DS_TRIGGERS=off leaves the triggers alone. |
| 1068 | uint8_t right[11], left[11]; | 1453 | if (s.config.ds_triggers != rt::gameinput::DsTriggerMode::Off) { |
| 1069 | ds_effect(want.right, right); | 1454 | uint8_t right[11], left[11]; |
| 1070 | ds_effect(want.left, left); | 1455 | ds_effect(want.right, right); |
| 1071 | if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) { | 1456 | ds_effect(want.left, left); |
| 1072 | uint8_t block[kDsEffectSize] = {}; | 1457 | if (!d->ds_sent_once || std::memcmp(right, o.ds_right, 11) || std::memcmp(left, o.ds_left, 11)) { |
| 1073 | block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect | 1458 | uint8_t block[kDsEffectSize] = {}; |
| 1074 | std::memcpy(block + 10, right, 11); | 1459 | block[0] = 0x04 | 0x08; // valid flags: right and left trigger effect |
| 1075 | std::memcpy(block + 21, left, 11); | 1460 | std::memcpy(block + 10, right, 11); |
| 1076 | if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) { | 1461 | std::memcpy(block + 21, left, 11); |
| 1077 | std::memcpy(o.ds_right, right, 11); | 1462 | if (SDL_SendGamepadEffect(d->pad, block, sizeof block)) { |
| 1078 | std::memcpy(o.ds_left, left, 11); | 1463 | std::memcpy(o.ds_right, right, 11); |
| 1079 | d->ds_sent_once = true; | 1464 | std::memcpy(o.ds_left, left, 11); |
| 1465 | d->ds_sent_once = true; | ||
| 1466 | } | ||
| 1080 | } | 1467 | } |
| 1081 | } | 1468 | } |
| 1082 | } else if (d->has_trigger_rumble) { | 1469 | } else if (d->has_trigger_rumble) { |
| @@ -1089,6 +1476,7 @@ void apply_output(Device* d, uint64_t now) { | |||
| 1089 | d->triggers_sent_at = now; | 1476 | d->triggers_sent_at = now; |
| 1090 | } | 1477 | } |
| 1091 | } | 1478 | } |
| 1479 | apply_effects(d, now); | ||
| 1092 | } | 1480 | } |
| 1093 | 1481 | ||
| 1094 | void refresh_battery(Device* d, uint64_t now) { | 1482 | void refresh_battery(Device* d, uint64_t now) { |
| @@ -1500,6 +1888,197 @@ void Device::SetRumbleState(const GameInputRumbleParams* params) { | |||
| 1500 | wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{}; | 1888 | wanted = params ? Rumble{params->lowFrequency, params->highFrequency, params->leftTrigger, params->rightTrigger} : Rumble{}; |
| 1501 | } | 1889 | } |
| 1502 | 1890 | ||
| 1891 | HRESULT Device::CreateForceFeedbackEffect(uint32_t motorIndex, const void* params, void** effect) { | ||
| 1892 | if (!effect) return E_POINTER; | ||
| 1893 | *effect = nullptr; | ||
| 1894 | if (!params || motorIndex >= info.forceFeedbackMotorCount) return E_INVALIDARG; | ||
| 1895 | const auto* p = static_cast<const GameInputForceFeedbackParams*>(params); | ||
| 1896 | // Only what the motor reported. SDL is not asked here: this is a title call, so the cached feature mask decides, | ||
| 1897 | // and the poll thread is what finds out if SDL refuses the effect anyway. | ||
| 1898 | if (!valid_kind(p->kind) || !(ff_features & kind_feature(p->kind))) return E_INVALIDARG; | ||
| 1899 | *effect = new ForceFeedbackEffect(this, motorIndex, *p); | ||
| 1900 | return S_OK; | ||
| 1901 | } | ||
| 1902 | |||
| 1903 | bool Device::IsForceFeedbackMotorPoweredOn(uint32_t motorIndex) { | ||
| 1904 | return motorIndex < info.forceFeedbackMotorCount && haptic != nullptr && status.load() != GameInputDeviceNoStatus; | ||
| 1905 | } | ||
| 1906 | |||
| 1907 | void Device::SetForceFeedbackMotorGain(uint32_t motorIndex, float masterGain) { | ||
| 1908 | std::lock_guard lock(g().mu); | ||
| 1909 | if (motorIndex < info.forceFeedbackMotorCount) motor_gain = std::clamp(masterGain, 0.0f, 1.0f); | ||
| 1910 | } | ||
| 1911 | |||
| 1912 | HRESULT Device::SetHapticMotorState(uint32_t motorIndex, const void* params) { | ||
| 1913 | std::lock_guard lock(g().mu); | ||
| 1914 | if (motorIndex >= haptic_motors) return E_INVALIDARG; | ||
| 1915 | if (!params) { // stop the motor | ||
| 1916 | haptic_intensity[motorIndex] = 0.0f; | ||
| 1917 | haptic_until[motorIndex] = 0; | ||
| 1918 | return S_OK; | ||
| 1919 | } | ||
| 1920 | const auto* p = static_cast<const GameInputHapticFeedbackParams*>(params); | ||
| 1921 | if (p->waveformIndex >= haptic_motor_info[motorIndex].waveformCount) return E_INVALIDARG; | ||
| 1922 | haptic_intensity[motorIndex] = std::clamp(p->intensity, 0.0f, 1.0f); | ||
| 1923 | // duration and repeatDelay are microseconds; playCount 0 plays until the state is set again. The poll thread sends | ||
| 1924 | // the level and drops it when the deadline passes. | ||
| 1925 | uint64_t total = p->playCount == 0 ? 0 : p->duration; | ||
| 1926 | if (p->playCount > 1) total = p->duration * p->playCount + p->repeatDelay * (p->playCount - 1); | ||
| 1927 | haptic_until[motorIndex] = total ? now_us() + total : 0; | ||
| 1928 | return S_OK; | ||
| 1929 | } | ||
| 1930 | |||
| 1931 | // ---- IGameInputForceFeedbackEffect ---------------------------------------------------------------- | ||
| 1932 | |||
| 1933 | ForceFeedbackEffect::ForceFeedbackEffect(Device* device, uint32_t motor, const GameInputForceFeedbackParams& params) | ||
| 1934 | : device_(device), motor_(motor), params_(params) { | ||
| 1935 | device_->AddRef(); | ||
| 1936 | std::lock_guard lock(g().mu); | ||
| 1937 | device_->effects.push_back(this); | ||
| 1938 | } | ||
| 1939 | |||
| 1940 | ForceFeedbackEffect::~ForceFeedbackEffect() { | ||
| 1941 | std::lock_guard lock(g().mu); | ||
| 1942 | std::vector<ForceFeedbackEffect*>& list = device_->effects; | ||
| 1943 | list.erase(std::remove(list.begin(), list.end(), this), list.end()); | ||
| 1944 | if (sdl_effect_ >= 0) { // SDL's effect is destroyed by the poll thread, which is the only thread that may | ||
| 1945 | device_->retired.push_back(sdl_effect_); | ||
| 1946 | sdl_effect_ = -1; | ||
| 1947 | } | ||
| 1948 | device_->Release(); | ||
| 1949 | } | ||
| 1950 | |||
| 1951 | HRESULT STDMETHODCALLTYPE ForceFeedbackEffect::QueryInterface(REFIID riid, void** out) { | ||
| 1952 | if (!out) return E_POINTER; | ||
| 1953 | if (same_guid(riid, IID_IUnknown) || same_guid(riid, IID_IGameInputForceFeedbackEffect)) { | ||
| 1954 | AddRef(); | ||
| 1955 | *out = static_cast<IGameInputForceFeedbackEffect*>(this); | ||
| 1956 | return S_OK; | ||
| 1957 | } | ||
| 1958 | *out = nullptr; | ||
| 1959 | return E_NOINTERFACE; | ||
| 1960 | } | ||
| 1961 | |||
| 1962 | ULONG STDMETHODCALLTYPE ForceFeedbackEffect::AddRef() { return ++refs_; } | ||
| 1963 | |||
| 1964 | ULONG STDMETHODCALLTYPE ForceFeedbackEffect::Release() { | ||
| 1965 | const ULONG r = --refs_; | ||
| 1966 | if (r == 0) delete this; | ||
| 1967 | return r; | ||
| 1968 | } | ||
| 1969 | |||
| 1970 | void STDMETHODCALLTYPE ForceFeedbackEffect::GetDevice(IGameInputDevice** device) { | ||
| 1971 | if (!device) return; | ||
| 1972 | device_->AddRef(); | ||
| 1973 | *device = device_; | ||
| 1974 | } | ||
| 1975 | |||
| 1976 | uint32_t STDMETHODCALLTYPE ForceFeedbackEffect::GetMotorIndex() { return motor_; } | ||
| 1977 | |||
| 1978 | float STDMETHODCALLTYPE ForceFeedbackEffect::GetGain() { | ||
| 1979 | std::lock_guard lock(g().mu); | ||
| 1980 | return gain_; | ||
| 1981 | } | ||
| 1982 | |||
| 1983 | void STDMETHODCALLTYPE ForceFeedbackEffect::SetGain(float gain) { | ||
| 1984 | std::lock_guard lock(g().mu); | ||
| 1985 | gain_ = std::clamp(gain, 0.0f, 1.0f); | ||
| 1986 | ++version_; | ||
| 1987 | } | ||
| 1988 | |||
| 1989 | void STDMETHODCALLTYPE ForceFeedbackEffect::GetParams(GameInputForceFeedbackParams* params) { | ||
| 1990 | if (!params) return; | ||
| 1991 | std::lock_guard lock(g().mu); | ||
| 1992 | *params = params_; | ||
| 1993 | } | ||
| 1994 | |||
| 1995 | bool STDMETHODCALLTYPE ForceFeedbackEffect::SetParams(const GameInputForceFeedbackParams* params) { | ||
| 1996 | if (!params || !valid_kind(params->kind)) return false; | ||
| 1997 | std::lock_guard lock(g().mu); | ||
| 1998 | params_ = *params; | ||
| 1999 | ++version_; | ||
| 2000 | return true; | ||
| 2001 | } | ||
| 2002 | |||
| 2003 | GameInputFeedbackEffectState STDMETHODCALLTYPE ForceFeedbackEffect::GetState() { | ||
| 2004 | std::lock_guard lock(g().mu); | ||
| 2005 | return state_; | ||
| 2006 | } | ||
| 2007 | |||
| 2008 | void STDMETHODCALLTYPE ForceFeedbackEffect::SetState(GameInputFeedbackEffectState state) { | ||
| 2009 | std::lock_guard lock(g().mu); | ||
| 2010 | state_ = state; | ||
| 2011 | ++version_; | ||
| 2012 | } | ||
| 2013 | |||
| 2014 | void ForceFeedbackEffect::orphan() { | ||
| 2015 | sdl_effect_ = -1; | ||
| 2016 | sdl_running_ = false; | ||
| 2017 | applied_ = 0; | ||
| 2018 | } | ||
| 2019 | |||
| 2020 | void ForceFeedbackEffect::sync(Device* d, uint64_t now, bool muted) { | ||
| 2021 | GameInputForceFeedbackParams params; | ||
| 2022 | float gain; | ||
| 2023 | GameInputFeedbackEffectState state; | ||
| 2024 | uint64_t version; | ||
| 2025 | { | ||
| 2026 | std::lock_guard lock(g().mu); | ||
| 2027 | params = params_; | ||
| 2028 | gain = gain_; | ||
| 2029 | state = state_; | ||
| 2030 | version = version_; | ||
| 2031 | } | ||
| 2032 | if (!d->haptic) return; | ||
| 2033 | // A stopped or paused effect is stopped in SDL: GameInput pauses one effect where SDL pauses the device, so a | ||
| 2034 | // pause here is a stop that keeps the parameters. LEONIDA_RUMBLE=0 silences this path like every other. | ||
| 2035 | if (state != GameInputFeedbackRunning || muted) { | ||
| 2036 | if (sdl_running_) { | ||
| 2037 | haptics().stop_effect(d->haptic, sdl_effect_); | ||
| 2038 | sdl_running_ = false; | ||
| 2039 | } | ||
| 2040 | return; | ||
| 2041 | } | ||
| 2042 | // An effect that played the length GameInput gave it is over, as the API says of a finished effect. The run is | ||
| 2043 | // forgotten so that a second SetState(Running) starts it again instead of expiring at once. | ||
| 2044 | if (!endless_ && run_for_ && now >= run_at_ + run_for_) { | ||
| 2045 | if (sdl_running_) { | ||
| 2046 | haptics().stop_effect(d->haptic, sdl_effect_); | ||
| 2047 | sdl_running_ = false; | ||
| 2048 | } | ||
| 2049 | endless_ = true; | ||
| 2050 | run_for_ = 0; | ||
| 2051 | std::lock_guard lock(g().mu); | ||
| 2052 | state_ = GameInputFeedbackStopped; | ||
| 2053 | return; | ||
| 2054 | } | ||
| 2055 | const bool stale = sdl_running_ && endless_ && now - run_at_ > kRumbleRefreshUs; | ||
| 2056 | if (sdl_running_ && version == applied_ && !stale) return; | ||
| 2057 | |||
| 2058 | SDL_HapticEffect fx; | ||
| 2059 | bool endless = true; | ||
| 2060 | uint32_t length_ms = kHapticHoldMs; | ||
| 2061 | if (!build_effect(params, gain, &endless, &length_ms, &fx)) { | ||
| 2062 | if (sdl_running_) haptics().stop_effect(d->haptic, sdl_effect_); | ||
| 2063 | sdl_running_ = false; | ||
| 2064 | return; | ||
| 2065 | } | ||
| 2066 | if (sdl_effect_ < 0) { | ||
| 2067 | sdl_effect_ = haptics().create_effect(d->haptic, &fx); // SDL refused: nothing to drive this effect | ||
| 2068 | if (sdl_effect_ < 0) return; | ||
| 2069 | } else if (!haptics().update_effect(d->haptic, sdl_effect_, &fx)) { | ||
| 2070 | return; | ||
| 2071 | } | ||
| 2072 | // GameInput's playCount 0 means "until stopped", which is what SDL's 0 iterations means. | ||
| 2073 | const uint32_t iterations = endless ? 0 : play_count(params); | ||
| 2074 | if (!haptics().run_effect(d->haptic, sdl_effect_, iterations)) return; | ||
| 2075 | sdl_running_ = true; | ||
| 2076 | applied_ = version; | ||
| 2077 | endless_ = endless; | ||
| 2078 | run_at_ = now; | ||
| 2079 | run_for_ = endless || iterations == 0 ? 0 : static_cast<uint64_t>(length_ms) * 1000ull * iterations; | ||
| 2080 | } | ||
| 2081 | |||
| 1503 | // ---- IGameInputDispatcher ---- | 2082 | // ---- IGameInputDispatcher ---- |
| 1504 | 2083 | ||
| 1505 | class Dispatcher final : public IGameInputDispatcher { | 2084 | class Dispatcher final : public IGameInputDispatcher { |
| @@ -1530,8 +2109,8 @@ public: | |||
| 1530 | } | 2109 | } |
| 1531 | return r; | 2110 | return r; |
| 1532 | } | 2111 | } |
| 1533 | // Runs the queued callbacks on the caller's thread. The quota is not enforced: the queue is short. | 2112 | // Runs the queued callbacks on the caller's thread within the quota (see deliver_within). |
| 1534 | bool STDMETHODCALLTYPE Dispatch(uint64_t) override { return deliver(); } | 2113 | bool STDMETHODCALLTYPE Dispatch(uint64_t quotaInMicroseconds) override { return deliver_within(quotaInMicroseconds); } |
| 1535 | HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { | 2114 | HRESULT STDMETHODCALLTYPE OpenWaitHandle(HANDLE* handle) override { |
| 1536 | if (!handle) return E_POINTER; | 2115 | if (!handle) return E_POINTER; |
| 1537 | *handle = nullptr; | 2116 | *handle = nullptr; |
| @@ -1881,6 +2460,8 @@ void set_keyboard_source(KeyDownFn key_down, HasFocusFn has_focus) { | |||
| 1881 | 2460 | ||
| 1882 | void set_cursor_source(CursorPosFn cursor_pos) { g_cursor_pos = cursor_pos ? cursor_pos : system_cursor_pos; } | 2461 | void set_cursor_source(CursorPosFn cursor_pos) { g_cursor_pos = cursor_pos ? cursor_pos : system_cursor_pos; } |
| 1883 | 2462 | ||
| 2463 | void set_haptic_source(const HapticApi* api) { g_haptic_api = api ? api : &kSdlHaptic; } | ||
| 2464 | |||
| 1884 | const KeyBinding* keyboard_bindings(int* count) { | 2465 | const KeyBinding* keyboard_bindings(int* count) { |
| 1885 | if (count) *count = static_cast<int>(std::size(kKeyBindings)); | 2466 | if (count) *count = static_cast<int>(std::size(kKeyBindings)); |
| 1886 | return kKeyBindings; | 2467 | return kKeyBindings; |