1 package com.badlogic.gdx.controllers.lwjgl3; 2 3 import org.lwjgl.glfw.GLFW; 4 5 import com.badlogic.gdx.Gdx; 6 import com.badlogic.gdx.controllers.Controller; 7 import com.badlogic.gdx.controllers.ControllerListener; 8 import com.badlogic.gdx.controllers.ControllerManager; 9 import com.badlogic.gdx.utils.Array; 10 11 public class Lwjgl3ControllerManager implements ControllerManager { 12 final Array<Controller> controllers = new Array<Controller>(); 13 final Array<Controller> polledControllers = new Array<Controller>(); 14 final Array<ControllerListener> listeners = new Array<ControllerListener>(); 15 16 public Lwjgl3ControllerManager() { 17 for(int i = GLFW.GLFW_JOYSTICK_1; i < GLFW.GLFW_JOYSTICK_LAST; i++) { 18 if(GLFW.glfwJoystickPresent(i) == GLFW.GLFW_TRUE) { 19 controllers.add(new Lwjgl3Controller(this, i)); 20 } 21 } 22 23 Gdx.app.postRunnable(new Runnable() { 24 @Override 25 public void run () { 26 pollState(); 27 Gdx.app.postRunnable(this); 28 } 29 }); 30 } 31 32 void pollState() { 33 for(int i = GLFW.GLFW_JOYSTICK_1; i < GLFW.GLFW_JOYSTICK_LAST; i++) { 34 if(GLFW.glfwJoystickPresent(i) == GLFW.GLFW_TRUE) { 35 boolean alreadyUsed = false; 36 for(int j = 0; j < controllers.size; j++) { 37 if(((Lwjgl3Controller)controllers.get(j)).index == i) { 38 alreadyUsed = true; 39 break; 40 } 41 } 42 if(!alreadyUsed) { 43 Lwjgl3Controller controller = new Lwjgl3Controller(this, i); 44 connected(controller); 45 } 46 } 47 } 48 49 polledControllers.addAll(controllers); 50 for(Controller controller: polledControllers) { 51 ((Lwjgl3Controller)controller).pollState(); 52 } 53 polledControllers.clear(); 54 } 55 56 @Override 57 public Array<Controller> getControllers () { 58 return controllers; 59 } 60 61 @Override 62 public void addListener (ControllerListener listener) { 63 listeners.add(listener); 64 } 65 66 @Override 67 public void removeListener (ControllerListener listener) { 68 listeners.removeValue(listener, true); 69 } 70 71 @Override 72 public void clearListeners () { 73 listeners.clear(); 74 } 75 76 void connected (Lwjgl3Controller controller) { 77 controllers.add(controller); 78 for(ControllerListener listener: listeners) { 79 listener.connected(controller); 80 } 81 } 82 83 void disconnected (Lwjgl3Controller controller) { 84 controllers.removeValue(controller, true); 85 for(ControllerListener listener: listeners) { 86 listener.disconnected(controller); 87 } 88 } 89 90 void axisChanged (Lwjgl3Controller controller, int axisCode, float value) { 91 for(ControllerListener listener: listeners) { 92 listener.axisMoved(controller, axisCode, value); 93 } 94 } 95 96 void buttonChanged (Lwjgl3Controller controller, int buttonCode, boolean value) { 97 for(ControllerListener listener: listeners) { 98 if(value) { 99 listener.buttonDown(controller, buttonCode); 100 } else { 101 listener.buttonUp(controller, buttonCode); 102 } 103 } 104 } 105 } 106