1 module gfm.sdl2.joystick; 2 3 import std.format : format; 4 import std..string; 5 6 import bindbc.sdl; 7 8 import gfm.sdl2.sdl; 9 10 final class SDLJoystick 11 { 12 private SDL_Joystick *_joystick = null; 13 private SDL2 _sdl = null; 14 15 public static int joystickCount() 16 { 17 return SDL_NumJoysticks(); 18 } 19 20 public static void runUpdate() 21 { 22 SDL_JoystickUpdate(); 23 } 24 25 public static bool update() 26 { 27 return (SDL_ENABLE == SDL_JoystickEventState(SDL_QUERY)); 28 } 29 30 public static void update(bool autoProc) 31 { 32 SDL_JoystickEventState(autoProc ? SDL_ENABLE : SDL_IGNORE); 33 } 34 35 this(SDL2 sdl2, int joystickIdx) 36 { 37 this._sdl = sdl2; 38 this._joystick = SDL_JoystickOpen(joystickIdx); 39 40 if (this._joystick is null) 41 this._sdl.throwSDL2Exception("SDL_JoystickOpen"); 42 } 43 44 this(SDL2 sdl2, string joystickName) 45 { 46 this._sdl = sdl2; 47 for (int i = 0; i < SDLJoystick.joystickCount(); i++) 48 { 49 if (joystickName == SDL_JoystickNameForIndex(i).fromStringz) 50 { 51 this._joystick = SDL_JoystickOpen(i); 52 53 if (this._joystick is null) 54 this._sdl.throwSDL2Exception("SDL_JoystickOpen"); 55 else 56 break; 57 } 58 } 59 60 throw new SDL2Exception("Failed to find a joystick matching name " ~ joystickName); 61 } 62 63 ~this() 64 { 65 if (this._joystick) 66 { 67 SDL_JoystickClose(this._joystick); 68 this._joystick = null; 69 } 70 } 71 72 @property string name() 73 { 74 return cast(string)SDL_JoystickName(this._joystick).fromStringz; 75 } 76 77 @property ubyte[16] guid() 78 { 79 return SDL_JoystickGetGUID(this._joystick).data; 80 } 81 82 @property string guidString() 83 { 84 return cast(string)SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(this._joystick)).fromStringz; 85 } 86 87 @property bool attached() 88 { 89 return SDL_JoystickGetAttached(this._joystick) == SDL_TRUE; 90 } 91 92 @property int numAxes() 93 { 94 return SDL_JoystickNumAxes(this._joystick); 95 } 96 97 @property int numBalls() 98 { 99 return SDL_JoystickNumBalls(this._joystick); 100 } 101 102 @property int numHats() 103 { 104 return SDL_JoystickNumHats(this._joystick); 105 } 106 107 @property int numButtons() 108 { 109 return SDL_JoystickNumButtons(this._joystick); 110 } 111 112 short getAxis(int idx) 113 { 114 return SDL_JoystickGetAxis(this._joystick, idx); 115 } 116 117 ubyte getHat(int idx) 118 { 119 return SDL_JoystickGetHat(this._joystick, idx); 120 } 121 122 void getBall(int idx, out int dx, out int dy) 123 { 124 if (0 != SDL_JoystickGetBall(this._joystick, idx, &dx, &dy)) 125 this._sdl.throwSDL2Exception("SDL_JoystickGetBall"); 126 } 127 128 bool getButton(int idx) 129 { 130 return (1 == SDL_JoystickGetButton(this._joystick, idx)); 131 } 132 }