summaryrefslogtreecommitdiff
path: root/src/input/joystick.cpp
blob: 21de2ad3df8cad59c6f5e93f1ed85f858e9435a6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/*
 *  The ManaPlus Client
 *  Copyright (C) 2004-2009  The Mana World Development Team
 *  Copyright (C) 2009-2010  The Mana Developers
 *  Copyright (C) 2011-2020  The ManaPlus Developers
 *  Copyright (C) 2020-2023  The ManaVerse Developers
 *
 *  This file is part of The ManaPlus Client.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "input/joystick.h"

#include "configuration.h"
#include "logger.h"
#include "settings.h"
#include "sdlshared.h"

#include "input/inputmanager.h"

#include "utils/foreach.h"
#include "utils/timer.h"

PRAGMA48(GCC diagnostic push)
PRAGMA48(GCC diagnostic ignored "-Wshadow")
#include <SDL.h>
PRAGMA48(GCC diagnostic pop)

#include "debug.h"

Joystick *joystick = nullptr;
int Joystick::joystickCount = 0;
bool Joystick::mEnabled = false;
bool Joystick::mInitialized = false;

Joystick::Joystick(const int no) :
    mDirection(0),
    mHatPosition(0),
    mJoystick(nullptr),
    mTolerance(0),
    mNumber(no >= joystickCount ? joystickCount : no),
    mAxesNumber(MAX_AXES),
    mButtonsNumber(MAX_BUTTONS),
    mUseHatForMovement(true),
    mUseInactive(false),
    mHaveHats(false),
    mKeyToAction(),
    mKeyToId(),
    mKeyTimeMap()
{
    for (int i = 0; i < MAX_AXES; i++)
        mAxesPositions[i] = 0;
    for (int i = 0; i < MAX_BUTTONS; i++)
        mActiveButtons[i] = false;
}

Joystick::~Joystick()
{
    close();
}

void Joystick::init()
{
    // +++ possible to use SDL_EventState with different joystick features.
    SDL_JoystickEventState(SDL_ENABLE);
    mEnabled = config.getBoolValue("joystickEnabled");
    detect();
}

void Joystick::detect()
{
    // close current joystick device
    if (joystick != nullptr)
    {
        delete joystick;
        joystick = nullptr;
    }

    // need to completely reinitialize joystick subsystem
    // because SDL does not support hotplugging
    if (mInitialized)
        SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
    SDL_InitSubSystem(SDL_INIT_JOYSTICK);
    mInitialized = true;

    joystickCount = SDL_NumJoysticks();
    logger->log("%i joysticks/gamepads found", joystickCount);
    for (int i = 0; i < joystickCount; i++)
        logger->log("- %s", SDL_JoystickNameForIndex(i));

    if (joystickCount > 0)
    {
        joystick = new Joystick(config.getIntValue("selectedJoystick"));
        if (mEnabled)
        {
            joystick->open();
            joystick->update();
        }
    }
}

bool Joystick::open()
{
    if (mNumber >= joystickCount)
        mNumber = joystickCount - 1;
    if (mNumber < 0)
    {
        logger->log1("error: incorrect joystick selection");
        return false;
    }
    logger->log("open joystick %d", mNumber);

    mJoystick = SDL_JoystickOpen(mNumber);

    if (mJoystick == nullptr)
    {
        logger->log("Couldn't open joystick: %s", SDL_GetError());
        return false;
    }

    mAxesNumber = SDL_JoystickNumAxes(mJoystick);
    mButtonsNumber = SDL_JoystickNumButtons(mJoystick);

    logger->log("Joystick: %i ", mNumber);
#ifdef USE_SDL2
    logger->log("Name: %s", SDL_JoystickName(mJoystick));
    SDL_JoystickGUID guid = SDL_JoystickGetGUID(mJoystick);
    std::string guidStr;
    for (int f = 0; f < 16; f ++)
        guidStr.append(strprintf("%02x", CAST_U32(guid.data[f])));
    logger->log("Guid: %s", guidStr.c_str());
#if SDL_VERSION_ATLEAST(2, 0, 6)
    logger->log("Device id: %u:%u.%u",
        CAST_U32(SDL_JoystickGetVendor(mJoystick)),
        CAST_U32(SDL_JoystickGetProduct(mJoystick)),
        CAST_U32(SDL_JoystickGetProductVersion(mJoystick)));

    SDL_JoystickType type = SDL_JoystickGetType(mJoystick);
    std::string typeStr;
    switch (type)
    {
        default:
        case SDL_JOYSTICK_TYPE_UNKNOWN:
            typeStr = "unknown";
            break;
        case SDL_JOYSTICK_TYPE_GAMECONTROLLER:
            typeStr = "game controller";
            break;
        case SDL_JOYSTICK_TYPE_WHEEL:
            typeStr = "wheel";
            break;
        case SDL_JOYSTICK_TYPE_ARCADE_STICK:
            typeStr = "arcade stick";
            break;
        case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
            typeStr = "flight stick";
            break;
        case SDL_JOYSTICK_TYPE_DANCE_PAD:
            typeStr = "dance pad";
            break;
        case SDL_JOYSTICK_TYPE_GUITAR:
            typeStr = "guitar";
            break;
        case SDL_JOYSTICK_TYPE_DRUM_KIT:
            typeStr = "drum kit";
            break;
        case SDL_JOYSTICK_TYPE_ARCADE_PAD:
            typeStr = "arcade pad";
            break;
        case SDL_JOYSTICK_TYPE_THROTTLE:
            typeStr = "throttle";
            break;
    }
    logger->log("Type: " + typeStr);
#endif  // SDL_VERSION_ATLEAST(2, 0, 6)
    // probably need aslo dump SDL_JoystickCurrentPowerLevel
#else  // USE_SDL2

    logger->log("Name: %s", SDL_JoystickName(mNumber));
#endif  // USE_SDL2

    logger->log("Axes: %i ", mAxesNumber);
    logger->log("Balls: %i", SDL_JoystickNumBalls(mJoystick));
    logger->log("Hats: %i", SDL_JoystickNumHats(mJoystick));
    logger->log("Buttons: %i", mButtonsNumber);

    mHaveHats = (SDL_JoystickNumHats(mJoystick) > 0);

    if (mAxesNumber > MAX_AXES)
        mAxesNumber = mAxesNumber;

    if (mButtonsNumber > MAX_BUTTONS)
        mButtonsNumber = MAX_BUTTONS;

#ifdef __SWITCH__
    config.setValue("joystickTolerance", 0.1F);
#endif
    mTolerance = config.getFloatValue("joystickTolerance");
    mUseHatForMovement = config.getBoolValue("useHatForMovement");
    mUseInactive = config.getBoolValue("useInactiveJoystick");

    return true;
}

void Joystick::close()
{
    logger->log("close joystick %d", mNumber);
    if (mJoystick != nullptr)
    {
        SDL_JoystickClose(mJoystick);
        mJoystick = nullptr;
    }
}

void Joystick::setNumber(const int n)
{
    if (mJoystick != nullptr)
    {
        SDL_JoystickClose(mJoystick);
        mNumber = n;
        open();
    }
    else
    {
        mNumber = n;
    }
}

void Joystick::logic()
{
    BLOCK_START("Joystick::logic")
    if (!mEnabled)
    {
        BLOCK_END("Joystick::logic")
        return;
    }

    mDirection = 0;

    if (mUseInactive ||
        settings.inputFocused != KeyboardFocus::Unfocused)
    {
        for (int i = 0; i < mAxesNumber; i++)
            mAxesPositions[i] = SDL_JoystickGetAxis(mJoystick, i);

        // X-Axis
        int position = mAxesPositions[0];
        if (position >= mTolerance * SDL_JOYSTICK_AXIS_MAX)
            mDirection |= RIGHT;
        else if (position <= mTolerance * SDL_JOYSTICK_AXIS_MIN)
            mDirection |= LEFT;

        // Y-Axis
        position = mAxesPositions[1];
        if (position <= mTolerance * SDL_JOYSTICK_AXIS_MIN)
            mDirection |= UP;
        else if (position >= mTolerance * SDL_JOYSTICK_AXIS_MAX)
            mDirection |= DOWN;

#ifdef DEBUG_JOYSTICK
        if (SDL_JoystickGetAxis(mJoystick, 2))
            logger->log("axis 2 pos: %d", SDL_JoystickGetAxis(mJoystick, 2));
        if (SDL_JoystickGetAxis(mJoystick, 3))
            logger->log("axis 3 pos: %d", SDL_JoystickGetAxis(mJoystick, 3));
        if (SDL_JoystickGetAxis(mJoystick, 4))
            logger->log("axis 4 pos: %d", SDL_JoystickGetAxis(mJoystick, 4));
#endif  // DEBUG_JOYSTICK

        if (mHaveHats)
        {
            // reading only hat 0
            const uint8_t hat = SDL_JoystickGetHat(mJoystick, 0);
            mHatPosition = 0;
            if ((hat & SDL_HAT_RIGHT) != 0)
                mHatPosition |= RIGHT;
            else if ((hat & SDL_HAT_LEFT) != 0)
                mHatPosition |= LEFT;
            if ((hat & SDL_HAT_UP) != 0)
                mHatPosition |= UP;
            else if ((hat & SDL_HAT_DOWN) != 0)
                mHatPosition |= DOWN;
            if ((mDirection == 0U) && mUseHatForMovement)
                mDirection = mHatPosition;
        }

        // Buttons
        for (int i = 0; i < mButtonsNumber; i++)
        {
            const bool state = (SDL_JoystickGetButton(mJoystick, i) == 1);
            mActiveButtons[i] = state;
            if (!state)
                resetRepeat(i);
#ifdef DEBUG_JOYSTICK
            if (mActiveButtons[i])
                logger->log("button: %d", i);
#endif  // DEBUG_JOYSTICK
        }
    }
    else
    {
        mHatPosition = 0;
        for (int i = 0; i < mAxesNumber; i++)
            mAxesPositions[i] = 0;
        for (int i = 0; i < mButtonsNumber; i++)
            mActiveButtons[i] = false;
    }
    BLOCK_END("Joystick::logic")
}

bool Joystick::buttonPressed(const int no) const
{
    if (!mEnabled)
        return false;
    if (no < 0)
        return false;
    if (no < MAX_BUTTONS)
        return mActiveButtons[no];
    if (!mUseHatForMovement)
    {
        if (no == KEY_UP)
            return (mHatPosition & UP) != 0;
        if (no == KEY_DOWN)
            return (mHatPosition & DOWN) != 0;
        if (no == KEY_LEFT)
            return (mHatPosition & LEFT) != 0;
        if (no == KEY_RIGHT)
            return (mHatPosition & RIGHT) != 0;
    }
    if (KEY_NEGATIVE_AXIS_FIRST <= no && no < KEY_POSITIVE_AXIS_FIRST)
    {
        const int axis = no - KEY_NEGATIVE_AXIS_FIRST;
        if (axis < RESERVED_AXES || axis >= mAxesNumber)
            return false;
        return mAxesPositions[axis] < mTolerance * SDL_JOYSTICK_AXIS_MIN;
    }
    if (KEY_POSITIVE_AXIS_FIRST <= no && no < KEY_END)
    {
        const int axis = no - KEY_POSITIVE_AXIS_FIRST;
        if (axis < RESERVED_AXES || axis >= mAxesNumber)
            return false;
        return mAxesPositions[axis] > mTolerance * SDL_JOYSTICK_AXIS_MAX;
    }
    return false;
}

void Joystick::getNames(STD_VECTOR <std::string> &names)
{
    names.clear();
    for (int i = 0; i < joystickCount; i++)
        names.push_back(SDL_JoystickNameForIndex(i));
}

void Joystick::update()
{
    inputManager.updateKeyActionMap(mKeyToAction, mKeyToId,
        mKeyTimeMap, InputType::JOYSTICK);
}

bool Joystick::isActionEvent(const SDL_Event &event)
{
    return getButtonFromEvent(event) >= 0;
}

KeysVector *Joystick::getActionVector(const SDL_Event &event)
{
    const int i = getButtonFromEvent(event);
    return getActionVectorByKey(i);
}

KeysVector *Joystick::getActionVectorByKey(const int i)
{
    if (i < 0 || (i >= mButtonsNumber && i < MAX_BUTTONS) || i >= KEY_END)
        return nullptr;
//    logger->log("button triggerAction: %d", i);
    if (mKeyToAction.find(i) != mKeyToAction.end())
        return &mKeyToAction[i];
    return nullptr;
}

InputActionT Joystick::getActionId(const SDL_Event &event)
{
    const int i = getButtonFromEvent(event);
    if (i < 0)
        return InputAction::NO_VALUE;
    if (mKeyToId.find(i) != mKeyToId.end())
        return mKeyToId[i];
    return InputAction::NO_VALUE;
}

int Joystick::getButtonFromEvent(const SDL_Event &event) const
{
    if (event.type == SDL_JOYBUTTONDOWN)
    {
        if (event.jbutton.which != mNumber)
            return -1;
        return event.jbutton.button;
    }
    if (!mUseHatForMovement && event.type == SDL_JOYHATMOTION)
    {
        // reading only hat 0
        if (event.jhat.which != mNumber || event.jhat.hat != 0)
            return -1;
        const int value = event.jhat.value;
        // SDL reports new hat position, not when d-pad button is pressed.
        // because of that we have to compare it to previously known state.
        if ((mHatPosition & UP) == 0 && (value & SDL_HAT_UP) != 0)
            return KEY_UP;
        if ((mHatPosition & DOWN) == 0 && (value & SDL_HAT_DOWN) != 0)
            return KEY_DOWN;
        if ((mHatPosition & LEFT) == 0 && (value & SDL_HAT_LEFT) != 0)
            return KEY_LEFT;
        if ((mHatPosition & RIGHT) == 0 && (value & SDL_HAT_RIGHT) != 0)
            return KEY_RIGHT;
    }
    if (event.type == SDL_JOYAXISMOTION)
    {
        if (event.jaxis.which != mNumber)
            return -1;
        const int axis = event.jaxis.axis;
        if (axis < RESERVED_AXES)
            return -1;
        if (event.jaxis.value < mTolerance * SDL_JOYSTICK_AXIS_MIN
            && mAxesPositions[axis] > mTolerance * SDL_JOYSTICK_AXIS_MIN)
            return KEY_NEGATIVE_AXIS_FIRST + axis;
        if (event.jaxis.value > mTolerance * SDL_JOYSTICK_AXIS_MAX
            && mAxesPositions[axis] < mTolerance * SDL_JOYSTICK_AXIS_MAX)
            return KEY_POSITIVE_AXIS_FIRST + axis;
    }
    return -1;
}

bool Joystick::isActionActive(const InputActionT index) const
{
    if (!validate())
        return false;

    const InputFunction &key = inputManager.getKey(index);
    for (size_t i = 0; i < inputFunctionSize; i ++)
    {
        const InputItem &val = key.values[i];
        if (val.type != InputType::JOYSTICK)
            continue;
        return buttonPressed(val.value);
    }
    return false;
}

bool Joystick::validate() const
{
    if (!mEnabled)
        return false;

    return mUseInactive ||
        settings.inputFocused != KeyboardFocus::Unfocused;
}

void Joystick::handleRepeat(const int time)
{
    BLOCK_START("Joystick::handleRepeat")
    FOR_EACH (KeyTimeMapIter, it, mKeyTimeMap)
    {
        bool repeat(false);
        const int key = (*it).first;
        if (key >= 0 && key < mButtonsNumber)
        {
            if (mActiveButtons[key])
                repeat = true;
        }
        if (!mUseHatForMovement)
        {
            if (key == KEY_UP && (mHatPosition & UP) != 0)
                repeat = true;
            if (key == KEY_DOWN && (mHatPosition & DOWN) != 0)
                repeat = true;
            if (key == KEY_LEFT && (mHatPosition & LEFT) != 0)
                repeat = true;
            if (key == KEY_RIGHT && (mHatPosition & RIGHT) != 0)
                repeat = true;
        }
        if (KEY_NEGATIVE_AXIS_FIRST <= key && key < KEY_POSITIVE_AXIS_FIRST)
        {
            const int axis = key - KEY_NEGATIVE_AXIS_FIRST;
            if (axis >= RESERVED_AXES && mAxesPositions[axis] < mTolerance * SDL_JOYSTICK_AXIS_MIN)
                repeat = true;
        }
        if (KEY_POSITIVE_AXIS_FIRST <= key && key < KEY_END)
        {
            const int axis = key - KEY_POSITIVE_AXIS_FIRST;
            if (axis >= RESERVED_AXES && mAxesPositions[axis] > mTolerance * SDL_JOYSTICK_AXIS_MAX)
                repeat = true;
        }
        if (repeat)
        {
            int &keyTime = (*it).second;
            if (time > keyTime && abs(time - keyTime)
                > SDL_DEFAULT_REPEAT_DELAY * 10)
            {
                keyTime = time;
                inputManager.triggerAction(getActionVectorByKey(key));
            }
        }
    }
    BLOCK_END("Joystick::handleRepeat")
}

void Joystick::resetRepeat(const int key)
{
    const KeyTimeMapIter it = mKeyTimeMap.find(key);
    if (it != mKeyTimeMap.end())
        (*it).second = tick_time;
}