Package jinputjoysticktestv2

Source Code of jinputjoysticktestv2.joystick

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package jinputjoysticktestv2;



import java.util.ArrayList;

import net.java.games.input.Component;
import net.java.games.input.Component.Identifier;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
import tigergui.GUI;
import tigergui.KeybindingController;
import tigergui.Communicator;
import org.apache.log4j.Logger;



/**
*
* @author darlin
*/
public class joystick implements Runnable{
   
     private ArrayList<Controller> foundControllers;
     GUI window = null;
     KeybindingController  keybindingController = null;
     static Logger logger = null;
    
     Communicator  communicator = null;
     double[] lastValues;
     public boolean isPolling = false;
     static int oldP = 0;
     static int oldL = 0;
     static int oldX = 0;
     static int oldY = 0;
   
boolean ZAxisTransform = false;
  int ZAxisMultiplier = 1;
  int ZAxisOffset = 0;
       
        boolean ZRotTransform = false;
  int ZRotMultiplier = 1;
  int ZRotOffset = 0;
      
        boolean XAxisTransform = false;
  int XAxisMultiplier = 1;
  int XAxisOffset = 0;
       
        boolean YAxisTransform = false;
  int YAxisMultiplier = 1;
  int YAxisOffset = 0;
       
        boolean hatTransform = false;
  int hatMultiplier = 1;
  int hatOffset = 0;
       
      boolean sliderTransform = false;
  int sliderMultiplier = 1;
  int sliderOffset = 0;
       
       
        // public stick and hat compass positions
  public static final int NUM_COMPASS_DIRS = 9;

  public static final int NW = 0;
  public static final int NORTH = 1;
  public static final int NE = 2;
  public static final int WEST = 3;
  public static final int NONE = 4; // default value
  public static final int EAST = 5;
  public static final int SW = 6;
  public static final int SOUTH = 7;
  public static final int SE = 8;
       
        private Component[] comps; // holds the components
  private int xAxisIdx, yAxisIdx, zAxisIdx, rzAxisIdx;
        private int povIdx; // index for the POV hat
       
    
    public joystick(GUI window, KeybindingController keybindingController, Communicator  communicator){
        this.window = window;
        this.keybindingController = keybindingController;
        this.communicator = communicator;
        logger = Logger.getLogger(joystick.class);
        window.txtLog.append("zainjowanie joisticka"+ "\n");
        foundControllers = new ArrayList<>();
        logger.error("w joystick");
        searchForControllers();
       
       
       
        // If at least one controller was found we start showing controller data on window.
        if(!foundControllers.isEmpty()){
            System.out.println("znaleziono kontroler");          
            window.txtLog.append("znaleziono kontroler"+ "\n");
            isPolling = true;
        }
        else {
            System.out.println("nie znaleziono kontrolera");
             window.txtLog.append("nie znaleziono kontrolera"+ "\n");
             isPolling = false;
           
        }
   
}
   
   
    public void run(){
        if(!foundControllers.isEmpty()){
            startControllerData2();         
        }      
    }
   
   
     private void searchForControllers() {
        
        
        Controller[] controllers = ControllerEnvironment.getDefaultEnvironment().getControllers();

        for(int i = 0; i < controllers.length; i++){
            Controller controller = controllers[i];
           
            if (
                    controller.getType() == Controller.Type.STICK ||
                    controller.getType() == Controller.Type.GAMEPAD ||
                    controller.getType() == Controller.Type.WHEEL ||
                    controller.getType() == Controller.Type.FINGERSTICK
               )
            {
                // Add new controller to the list of all controllers.
                foundControllers.add(controller);
               
                // Add new controller to the list on the window.
               window.txtLog.append(controller.getName() + " - " + controller.getType().toString() + " type" + "\n");
               window.addControllerName(controller.getName() + " - " + controller.getType().toString() + " type");
            }
        }
    }
   
   
      private void startControllerData2(){
         
          int selectedControllerIndex = window.getSelectedControllerName();
          Controller controller = foundControllers.get(selectedControllerIndex);
        
          if (controller == null) {
          System.out.println("controller is null - can not poll");
      }

      /* Get all the axis and buttons */
      Component[] components = controller.getComponents();
      lastValues = new double[components.length];
                        findCompIndices(controller);

      isPolling = true;
      while (isPolling) {

        /* Poll the controller */
        controller.poll();

        // StringBuffer buffer = new StringBuffer();

        // TODO - selectively publish ... publish Direction? Yes
        /* For each component, get it's name, and it's current value */

        // FIXME - switch statement (it's Java 7 !)
        for (int i = 0; i < components.length; i++) {


          Component component = components[i];
          Identifier id = component.getIdentifier();

          String n = components[i].getName();
          float data = components[i].getPollData();

          // buffer.append(n);
          // TODO - invoke based on
          // invoke(String.trim(component.getName()),
          // mapMultiplier(getName()), mapOffset(getName()) - REFACTOR
          // REFACTOR !!! use switch statement
         
                                         if (Identifier.Axis.Z.equals(id)) {
            if (lastValues[i] != data) {
              if (ZAxisTransform) {
                invoke("ZAxis", (int) (ZAxisMultiplier * data) + ZAxisOffset);
              } else {
                invoke("ZAxisRaw", data);
              }
            }

          } else if (Identifier.Axis.RZ.equals(id)) {
            if (lastValues[i] != data) {
              if (ZRotTransform) {
                invoke("ZRotation", (int) (ZRotMultiplier * data) + ZRotOffset);
              } else {
                invoke("ZRotationRaw", data);
              }
            }
          } else if (Identifier.Axis.X.equals(id)) {
            if (lastValues[i] != data) {
              if (XAxisTransform) {
                invoke("XAxis", (int) (XAxisMultiplier * data) + XAxisOffset);
              } else {
                invoke("XAxisRaw", data);
              }
            }
          } else if (Identifier.Axis.Y.equals(id)) {
            if (lastValues[i] != data) {
              if (YAxisTransform) {
                invoke("YAxis", (int) (YAxisMultiplier * data) + YAxisOffset);
              } else {
                invoke("YAxisRaw", data);
              }
            }
          } else if (Identifier.Axis.POV.equals(id)) {
            if (lastValues[i] != data) {
              if (hatTransform) {
                invoke("hatSwitch", (int) (hatMultiplier * data) + hatOffset);
              } else {
                invoke("hatSwitchRaw", data);
              }
            }
                                               
                                               
                                               
                                                } else if (Identifier.Axis.SLIDER.equals(id)) {
            if (lastValues[i] != data) {
              if (sliderTransform) {
                invoke("slider", (int) (sliderMultiplier * data) + sliderOffset);
              } else {
                invoke("sliderRaw", data);
                                                                System.out.println("sliderRaw" + data);
              }
            }
                                               
                                               
            // WTF ??? - A on Linux _0 on Windows, really? I mean
            // really? Why?
          } else if (Identifier.Button.A.equals(id) || Identifier.Button._0.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button1", pos);
            }
          } else if (Identifier.Button.B.equals(id) || Identifier.Button._1.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button2", pos);
            }
          } else if (Identifier.Button.C.equals(id) || Identifier.Button._2.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button3", pos);
            }
          } else if (Identifier.Button.X.equals(id) || Identifier.Button._3.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button4", pos);
            }
          } else if (Identifier.Button.Y.equals(id) || Identifier.Button._4.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button5", pos);
            }
          } else if (Identifier.Button.Z.equals(id) || Identifier.Button._5.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button6", pos);
            }
          } else if (Identifier.Button.LEFT_THUMB.equals(id) || Identifier.Button._6.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button7", pos);
            }
          } else if (Identifier.Button.RIGHT_THUMB.equals(id) || Identifier.Button._7.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button8", pos);
            }
          } else if (Identifier.Button.LEFT_THUMB2.equals(id) || Identifier.Button._8.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button9", pos);
            }
          } else if (Identifier.Button.RIGHT_THUMB2.equals(id) || Identifier.Button._9.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button10", pos);
            }
          } else if (Identifier.Button.SELECT.equals(id) || Identifier.Button._10.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button11", pos);
            }
          } else if (Identifier.Button.UNKNOWN.equals(id) || Identifier.Button._11.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button12", pos);
            }
          } else if (Identifier.Button._12.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button13", pos);
            }
         
                                        } else if (Identifier.Button._13.equals(id)) {
            int pos = (int) data;
            if (lastValues[i] != data) {
              invoke("button14", pos);
            }                                         
                                               
                                       
                                        } else {
            System.out.println(String.format("unknown identifier %s", id.toString()));
          }

          lastValues[i] = data;
                                        System.out.println("kierunek XY: " + getXYStickDir()+ " " + comps[xAxisIdx].getPollData() + " " + comps[yAxisIdx].getPollData());

          /*
           * buffer.append(": "); if (components[i].isAnalog()) { //
           * Get the value at the last poll of this component
           * buffer.append(components[i].getPollData()); } else {
           * buffer.append(components[i].getPollData()); if
           * (components[i].getPollData() == 1.0f) {
           * buffer.append("On"); } else { buffer.append("Off"); } }
           */
        }

        // log.info(buffer.toString());
        /*
         * Sleep for 20 millis, this is just so the example doesn't
         * thrash the system. FIXME - can a polling system be avoided -
         * could this block with the JNI code?
         */
        try {
          Thread.sleep(20);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
 
     
     
     
     
     
      final public Object invoke(String method, Object... params) {
    Object retobj = null;
    Class<?> c;
    c = this.getClass();
                return retobj;
      }
     
      private int findCompIndex(Component[] comps, Component.Identifier id, String nm) {
    Component c;
    for (int i = 0; i < comps.length; i++) {
      c = comps[i];
      if ((c.getIdentifier() == id) && !c.isRelative()) {
        System.out.println("Found " + c.getName() + "; index: " + i);
        return i;
      }
    }

    System.out.println("No " + nm + " component found");
    return -1;
  } // end of findCompIndex()
     
      private void findCompIndices(Controller controller)
  /*
   * Store the indices for the analog sticks axes (x,y) and (z,rz), POV hat,
   * and button components of the controller.
   */
  {
    comps = controller.getComponents();
    if (comps.length == 0) {
      System.out.println("No Components found");
      System.exit(0);
    } else
      System.out.println("Num. Components: " + comps.length);

    // get the indices for the axes of the analog sticks: (x,y) and (z,rz)
    xAxisIdx = findCompIndex(comps, Component.Identifier.Axis.X, "x-axis");
    yAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Y, "y-axis");

    zAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Z, "z-axis");
    rzAxisIdx = findCompIndex(comps, Component.Identifier.Axis.RZ, "rz-axis");

    // get POV hat index
    povIdx = findCompIndex(comps, Component.Identifier.Axis.POV, "POV hat");

    //findButtons(comps);
  } // end of findCompIndices()
     
     
      public int getXYStickDir()
  // return the (x,y) analog stick compass direction
  {
    if ((xAxisIdx == -1) || (yAxisIdx == -1)) {
      System.out.println("(x,y) axis data unavailable");
      return NONE;
    } else
      return getCompassDir(xAxisIdx, yAxisIdx);
  } // end of getXYStickDir()
     
     
     
      private int getCompassDir(int xA, int yA)
  // Return the axes as a single compass value
  {
    float xCoord = comps[xA].getPollData();
    float yCoord = comps[yA].getPollData();
    // log.info("(x,y): (" + xCoord + "," + yCoord + ")");

    int xc = Math.round(xCoord);
    int yc = Math.round(yCoord);
    // log.info("Rounded (x,y): (" + xc + "," + yc + ")");

    if ((yc == -1) && (xc == -1)) // (y,x)
      return NW;
    else if ((yc == -1) && (xc == 0))
      return NORTH;
    else if ((yc == -1) && (xc == 1))
      return NE;
    else if ((yc == 0) && (xc == -1))
      return WEST;
    else if ((yc == 0) && (xc == 0))
      return NONE;
    else if ((yc == 0) && (xc == 1))
      return EAST;
    else if ((yc == 1) && (xc == -1))
      return SW;
    else if ((yc == 1) && (xc == 0))
      return SOUTH;
    else if ((yc == 1) && (xc == 1))
      return SE;
    else {
      System.out.println("Unknown (x,y): (" + xc + "," + yc + ")");
      return NONE;
    }
  } // end of getCompassDir()
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    
      private void startControllerData(){
        while(true)
        {
            // Currently selected controller.
            int selectedControllerIndex = window.getSelectedControllerName();
            Controller controller = foundControllers.get(selectedControllerIndex);

            // Pull controller for current data, and break while loop if controller is disconnected.
            if( !controller.poll() ){
                window.showControllerDisconnected();
                break;
            }
           
             // X axis and Y axis
            int axisValueInPercentage =0;
            int xAxisPercentage = 0;
            int yAxisPercentage = 0;
           
             Component[] components = controller.getComponents();
            for(int i=0; i < components.length; i++)
            {
                Component component = components[i];
                Component.Identifier componentIdentifier = component.getIdentifier();
               
                //System.out.println("component name: " + component.getName());
            
                // Buttons
               
               // Axes  
                if(component.isAnalog()){
                    float axisValue = component.getPollData();
                   
               //     if (axisValue >0 && axisValue <1.5){
               //      axisValueInPercentage = getAxisValueInPercentageDown(axisValue, component.getName());}
              //      if (axisValue <0 && axisValue > -1.5){
              //       axisValueInPercentage = getAxisValueInPercentageUP(axisValue, component.getName());}
                    //System.out.println("component name axisValue: " + component.getName()+ axisValueInPercentage);
                   
                    //window.txtLog.append(component.getName()+ axisValueInPercentage +"\n");
                   
                    // X axis
                    if(componentIdentifier == Component.Identifier.Axis.X){
                        axisValueInPercentage = getAxisValueInPercentageX(axisValue, component.getName());
                        yAxisPercentage = axisValueInPercentage;
                        System.out.println("X: " +  yAxisPercentage);
                       setJoystickData('X',  yAxisPercentage);
                        continue; // Go to next component.
                    }
                    // Y axis
                    if(componentIdentifier == Component.Identifier.Axis.Y){
                        axisValueInPercentage = getAxisValueInPercentageY(axisValue, component.getName());
                        yAxisPercentage = axisValueInPercentage;
                       System.out.println("Y: " + yAxisPercentage);
                      setJoystickData('Y', yAxisPercentage);
                        continue; // Go to next component.
                    }
                   
                    // Throtlle Oœ
                                 
                    if(component.getName().contains("Oœ")){
                         xAxisPercentage = getThrottleValueInPercentage(axisValue);
                       System.out.println("Throtlle L : " + xAxisPercentage);
                       setJoystickData('L', xAxisPercentage);
                        continue; // Go to next component.
                    }
                    // Throtlle Suwak
                    if(component.getName().contains("Suwak")){
                         xAxisPercentage =  getThrottleValueInPercentage(axisValue);
                       System.out.println("Throtlle R : " + xAxisPercentage);
                      
                       setJoystickData('P', xAxisPercentage);
                        continue; // Go to next component.
                    }
                   
                 
                  
                    
              
               }
            }
           
            // We have to give processor some rest.
            try {
                Thread.sleep(250);
            } catch (InterruptedException ex) {
                //Logger.getLogger(JoystickTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
      }
    
    public int getAxisValueInPercentageY(float axisValue, String name)
    {
       // if((name.contains("Oœ")) || (name.contains("Suwak")))
       //     getThrottleValueInPercentage(axisValue);
        //return (int)(((2 - (1 - axisValue)) * 10) / 2);
        if (axisValue >0 && axisValue <1.5) {   
            keybindingController.setDirection('b');
        return (int)((( 2- (1 - axisValue)) * 10)-10);
        }else  if (axisValue <0 && axisValue > -1.5){
            keybindingController.setDirection('f');
               return (int)((((1)- (1 - axisValue)) * (-10)) );
        }else keybindingController.setDirection('s');
                return(0);
        }
       
    }
   
  
   
     public int getAxisValueInPercentageX(float axisValue, String name)
    {
       // if((name.contains("Oœ")) || (name.contains("Suwak")))
       //     getThrottleValueInPercentage(axisValue);
        //return (int)(((2 - (1 - axisValue)) * 10) / 2);
        if (axisValue >0 && axisValue <1.5) {   
           // keybindingController.setDirection('p');
        return (int)((( 2- (1 - axisValue)) * 10)-10);
        }else  if (axisValue <0 && axisValue > -1.5){
          //  keybindingController.setDirection('l');
               return (int)((((1)- (1 - axisValue)) * (-10)) );
        }else { // keybindingController.setDirection('s');
                return(0);
        }
       
    }
   
   
   
     public int getThrottleValueInPercentage(float axisValue)
    {
        keybindingController.setDirection('i');
         return (int)(((2 - (1 - axisValue)) * 10) / 2);
      
    }
    
    
    public void setJoystickData(char c, int a){
       
        if(c == 'P'){      
         if (communicator.getConnected() && ((a <  oldP)||(a > oldP)) ){
    
         keybindingController.setRightThrottle(a);
         keybindingController.updateLabels();
         oldP =a;
         }
        }
       
      
         if(c == 'L'){      
         if (communicator.getConnected() && ((a <  oldL)||(a > oldL)) ){
      
         keybindingController.setLeftThrottle(a);
         keybindingController.updateLabels();
         oldL =a;
         }
        }
       
        if(c == 'X'){      
         if (communicator.getConnected() && ((a <  oldX)||(a > oldX)) ){
            
         keybindingController.setRightThrottle(a);
         keybindingController.updateLabels();
         oldX =a;
         }
        }
       
        if(c == 'Y'){      
         if (communicator.getConnected() && ((a < oldY)||(a > oldY))  ){
            
         keybindingController.setLeftThrottle(a);
         keybindingController.updateLabels();
         oldY =a;
         }
        }
         
    }
   
   
    }
TOP

Related Classes of jinputjoysticktestv2.joystick

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.