SDL++
C++wrapperfortheSDLlibrary.
|
00001 00021 #ifndef SDL_DEVICES_JOYSTICK_H 00022 #define SDL_DEVICES_JOYSTICK_H 00023 00024 #include <string> 00025 #include <stdexcept> 00026 #include <utility> 00027 00028 #include <SDL.h> 00029 00030 #include "sdlpp/subsystem/Subsystem.h" 00031 #include "sdlpp/event/Components.h" 00032 00033 namespace sdl { 00034 namespace devices { 00035 using namespace misc; 00036 00041 class Joystick { 00042 public: 00048 Joystick (int index) : joystick_ (open (index)) { 00049 SDL_PumpEvents (); 00050 SDL_Event* joyEvents = new SDL_Event[18]; 00051 SDL_PeepEvents (joyEvents, 18, SDL_GETEVENT, SDL_EVENTMASK (SDL_JOYAXISMOTION) | SDL_EVENTMASK (SDL_JOYBUTTONUP) | SDL_EVENTMASK (SDL_JOYBUTTONDOWN)); 00052 delete[] joyEvents; 00053 }; 00054 00058 ~Joystick () { SDL_JoystickClose (joystick_); }; 00059 00065 std::string name () { return SDL_JoystickName (SDL_JoystickIndex (joystick_)); }; 00066 00072 int index () { return SDL_JoystickIndex (joystick_); }; 00073 00079 int numAxes () { return SDL_JoystickNumAxes (joystick_); }; 00080 00086 int numButtons () { return SDL_JoystickNumButtons (joystick_); }; 00087 00093 int numHats () { return SDL_JoystickNumHats (joystick_); }; 00094 00100 int numTrackballs () { return SDL_JoystickNumBalls (joystick_); }; 00101 00109 short axisPosition (int axis) { return SDL_JoystickGetAxis (joystick_, axis); }; 00110 00118 bool isPressed (int button) { return SDL_JoystickGetButton (joystick_, button) == 1; }; 00119 00127 char hatState (int hat) { return SDL_JoystickGetHat (joystick_, hat); }; 00128 00138 pair<int, int> trackballMotion (int trackball) { 00139 pair<int, int> res = make_pair (0, 0); 00140 if (SDL_JoystickGetBall (joystick_, trackball, &res.first, &res.second) == -1) 00141 throw runtime_error ("Unable to determine trackball motion"); 00142 return res; 00143 }; 00144 00145 private: 00151 Joystick (const Joystick& rhs); 00152 00160 Joystick& operator= (const Joystick& rhs); 00161 00171 SDL_Joystick* open (int index) { 00172 if (index > subsystem::Joystick::instance ().numJoysticks () - 1) 00173 throw runtime_error ("Invalid joystick index."); 00174 00175 SDL_Joystick* joystick = SDL_JoystickOpen (index); 00176 if (joystick == NULL) 00177 throw runtime_error ("Failed to open joystick."); 00178 return joystick; 00179 }; 00180 00184 SDL_Joystick* joystick_; 00185 }; //Joystick 00186 }; //devices 00187 }; //sdl 00188 00189 #endif //SDL_DEVICES_JOYSTICK_H 00190