Merge 'remotes/trunk'
[0ad.git] / source / ps / Joystick.cpp
blob73c05e7ffcd31914b51c26e403351f47f1c4f4ad
1 /* Copyright (C) 2021 Wildfire Games.
2 * This file is part of 0 A.D.
4 * 0 A.D. is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
9 * 0 A.D. is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
18 #include "precompiled.h"
20 #include "Joystick.h"
22 #include "lib/external_libraries/libsdl.h"
23 #include "ps/CLogger.h"
24 #include "ps/ConfigDB.h"
26 CJoystick g_Joystick;
28 CJoystick::CJoystick() :
29 m_Joystick(NULL), m_Deadzone(0)
33 void CJoystick::Initialise()
35 bool joystickEnable = false;
36 if (!CConfigDB::IsInitialised())
37 return;
38 CFG_GET_VAL("joystick.enable", joystickEnable);
39 if (!joystickEnable)
40 return;
42 CFG_GET_VAL("joystick.deadzone", m_Deadzone);
44 if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0)
46 LOGERROR("CJoystick::Initialise failed to initialise joysticks (\"%s\")", SDL_GetError());
47 return;
50 int numJoysticks = SDL_NumJoysticks();
52 LOGMESSAGE("Found %d joystick(s)", numJoysticks);
54 for (int i = 0; i < numJoysticks; ++i)
56 SDL_Joystick* stick = SDL_JoystickOpen(i);
57 if (!stick)
59 LOGERROR("CJoystick::Initialise failed to open joystick %d (\"%s\")", i, SDL_GetError());
60 continue;
62 const char* name = SDL_JoystickName(stick);
63 LOGMESSAGE("Joystick %d: %s", i, name);
64 SDL_JoystickClose(stick);
67 if (numJoysticks)
69 SDL_JoystickEventState(SDL_ENABLE);
71 // Always pick the first joystick, and assume that's the right one
72 m_Joystick = SDL_JoystickOpen(0);
73 if (!m_Joystick)
74 LOGERROR("CJoystick::Initialise failed to open joystick (\"%s\")", SDL_GetError());
78 bool CJoystick::IsEnabled()
80 return (m_Joystick != NULL);
83 float CJoystick::GetAxisValue(int axis)
85 if (!m_Joystick || axis < 0 || axis >= SDL_JoystickNumAxes(m_Joystick))
86 return 0.f;
88 int16_t val = SDL_JoystickGetAxis(m_Joystick, axis);
90 // Normalize values into the range [-1, +1] excluding the deadzone around 0
91 float norm;
92 if (val > m_Deadzone)
93 norm = (val - m_Deadzone) / (float)(32767 - m_Deadzone);
94 else if (val < -m_Deadzone)
95 norm = (val + m_Deadzone) / (float)(32767 - m_Deadzone);
96 else
97 norm = 0.f;
99 return norm;