File: Joystick.cpp

package info (click to toggle)
spring 103.0%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,720 kB
  • ctags: 63,685
  • sloc: cpp: 368,283; ansic: 33,988; python: 12,417; java: 12,203; awk: 5,879; sh: 1,846; xml: 655; perl: 405; php: 211; objc: 194; makefile: 77; sed: 2
file content (106 lines) | stat: -rw-r--r-- 2,156 bytes parent folder | download
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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include "InputHandler.h"
#include "Joystick.h"

#include <SDL.h>

#include "System/Config/ConfigHandler.h"
#include "System/Log/ILog.h"
#include "System/EventHandler.h"

CONFIG(bool, JoystickEnabled).defaultValue(true).headlessValue(false);
CONFIG(int, JoystickUse).defaultValue(0);

Joystick* stick = NULL;

void InitJoystick()
{
	const bool useJoystick = configHandler->GetBool("JoystickEnabled");
	if (useJoystick)
	{
		const int err = SDL_InitSubSystem(SDL_INIT_JOYSTICK);
		if (err == -1)
		{
			LOG_L(L_ERROR, "Could not initialise joystick subsystem: %s",
					SDL_GetError());
			return;
		}
		else
		{
			stick = new Joystick();
		}
	};
}

void FreeJoystick() {
	if (stick != NULL) {
		delete stick;
		stick = NULL;
	}
}

Joystick::Joystick()
	: myStick(nullptr)
{
	const int numSticks = SDL_NumJoysticks();
	LOG("Joysticks found: %i", numSticks);
	if (numSticks <= 0)
		return;

	const int stickNum = configHandler->GetInt("JoystickUse");

	myStick = SDL_JoystickOpen(stickNum);

	if (myStick)
	{
		LOG("Using joystick %i: %s", stickNum, SDL_JoystickName(myStick));
		inputCon = input.AddHandler(boost::bind(&Joystick::HandleEvent, this, _1));
	}
	else
	{
		LOG_L(L_ERROR, "Joystick %i not found", stickNum);
	}
}

Joystick::~Joystick()
{
	if (myStick)
		SDL_JoystickClose(myStick);
}

bool Joystick::HandleEvent(const SDL_Event& event)
{
	switch (event.type) {
		case SDL_JOYAXISMOTION:
		{
			eventHandler.JoystickEvent("JoyAxis", event.jaxis.axis, event.jaxis.value);
			break;
		}
		case SDL_JOYHATMOTION:
		{
			eventHandler.JoystickEvent("JoyHat", event.jhat.hat, event.jhat.value);
			break;
		}
		case SDL_JOYBUTTONDOWN:
		{
			eventHandler.JoystickEvent("JoyButtonDown", event.jbutton.button, event.jbutton.state);
			break;
		}
		case SDL_JOYBUTTONUP:
		{
			eventHandler.JoystickEvent("JoyButtonUp", event.jbutton.button, event.jbutton.state);
			break;
		}
		case SDL_JOYDEVICEADDED: //TODO
			LOG("Joystick has been added");
			break;
		case SDL_JOYDEVICEREMOVED:
			LOG("Joystick has been removed");
			break;
		default:
		{
		}
	}
	return false;
}