Guest User

GamepadJoyInput.java

a guest
Sep 12th, 2013
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 27.30 KB | None | 0 0
  1. /*
  2.  * Copyright (c) 2009-2012 jMonkeyEngine
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions are
  7.  * met:
  8.  *
  9.  * * Redistributions of source code must retain the above copyright
  10.  *   notice, this list of conditions and the following disclaimer.
  11.  *
  12.  * * Redistributions in binary form must reproduce the above copyright
  13.  *   notice, this list of conditions and the following disclaimer in the
  14.  *   documentation and/or other materials provided with the distribution.
  15.  *
  16.  * * Neither the name of 'jMonkeyEngine' nor the names of its contributors
  17.  *   may be used to endorse or promote products derived from this software
  18.  *   without specific prior written permission.
  19.  *
  20.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21.  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  22.  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  23.  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  24.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  25.  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  26.  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  27.  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  28.  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  29.  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  30.  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31.  */
  32.  
  33. package com.jme3.input.android;
  34.  
  35. import android.app.Activity;
  36. import android.content.Context;
  37. import android.hardware.SensorManager;
  38. import android.os.Vibrator;
  39. import android.view.InputDevice;
  40. import android.view.KeyEvent;
  41. import android.view.MotionEvent;
  42. import android.view.Surface;
  43. import android.view.View;
  44. import com.jme3.input.AbstractJoystick;
  45. import com.jme3.input.DefaultJoystickAxis;
  46. import com.jme3.input.DefaultJoystickButton;
  47. import com.jme3.input.InputManager;
  48. import com.jme3.input.JoyInput;
  49. import com.jme3.input.Joystick;
  50. import com.jme3.input.JoystickAxis;
  51. import com.jme3.input.JoystickButton;
  52. import com.jme3.input.SensorJoystickAxis;
  53. import com.jme3.input.RawInputListener;
  54. import com.jme3.input.event.JoyAxisEvent;
  55. import com.jme3.input.event.JoyButtonEvent;
  56. import com.jme3.math.FastMath;
  57. import com.jme3.system.android.JmeAndroidSystem;
  58. import com.jme3.util.IntMap;
  59. import com.jme3.util.IntMap.Entry;
  60. import java.util.ArrayList;
  61. import java.util.HashMap;
  62. import java.util.List;
  63. import java.util.Map;
  64. import java.util.logging.Level;
  65. import java.util.logging.Logger;
  66. import net.java.games.input.Component;
  67.  
  68. /**
  69.  * GamepadJoyInput converts the Android Sensor system into Joystick events.
  70.  * A single joystick is configured and includes data for all configured sensors
  71.  * as seperate axes of the joystick.
  72.  *
  73.  * Each axis is named accounting to the static strings in SensorJoystickAxis.
  74.  * Refer to the strings defined in SensorJoystickAxis for a list of supported
  75.  * sensors and their axis data.  Each sensor type defined in SensorJoystickAxis
  76.  * will be attempted to be configured.  If the device does not support a particular
  77.  * sensor, the axis will return null if joystick.getAxis(String name) is called.
  78.  *
  79.  * The joystick.getXAxis and getYAxis methods of the joystick are configured to
  80.  * return the device orientation values in the device's X and Y directions.
  81.  *
  82.  * This joystick also supports the joystick.rumble(rumbleAmount) method.  In this
  83.  * case, when joystick.rumble(rumbleAmount) is called, the Android device will vibrate
  84.  * if the device has a built in vibrate motor.
  85.  *
  86.  * Because Andorid does not allow for the user to define the intensity of the
  87.  * vibration, the rumble amount (ie strength) is converted into vibration pulses
  88.  * The stronger the strength amount, the shorter the delay between pulses.  If
  89.  * amount is 1, then the vibration stays on the whole time.  If amount is 0.5,
  90.  * the vibration will a pulse of equal parts vibration and delay.
  91.  * To turn off vibration, set rumble amount to 0.
  92.  *
  93.  * MainActivity needs the following line to enable Joysticks on Android platforms
  94.  *    joystickEventsEnabled = true;
  95.  * This is done to allow for battery conservation when sensor data is not required
  96.  * by the application.
  97.  *
  98.  * To use the joystick rumble feature, the following line needs to be
  99.  * added to the Android Manifest File
  100.  *     <uses-permission android:name="android.permission.VIBRATE"/>
  101.  *
  102.  * @author iwgeric
  103.  */
  104. public class GamepadJoyInput implements JoyInput, View.OnGenericMotionListener, View.OnKeyListener {
  105.     private final static Logger logger = Logger.getLogger(GamepadJoyInput.class.getName());
  106.  
  107.     private Activity activity = null;
  108.     private InputManager inputManager = null;
  109.     private android.hardware.input.InputManager androidInputManager = null;
  110.     private int[] devicesIDs;
  111.     private InputDevice inputDevice = null;
  112.     private Vibrator vibrator = null;
  113.     private boolean vibratorActive = false;
  114.     private long maxRumbleTime = 250;  // 250ms
  115.     private RawInputListener listener = null;
  116.     private IntMap<SensorData> sensors = new IntMap<SensorData>();
  117.     private Map<InputDevice, AndroidJoystick> joystickIndex = new HashMap<InputDevice, AndroidJoystick>();
  118.     private AndroidJoystick[] joysticks;
  119.     private int lastRotation = 0;
  120.     private boolean initialized = false;
  121.     private boolean loaded = false;
  122.     private View mView = null;
  123.  
  124.     private final ArrayList<JoyAxisEvent> eventQueue = new ArrayList<JoyAxisEvent>();
  125.     private final ArrayList<JoyButtonEvent> buttoneventQueue = new ArrayList<JoyButtonEvent>();
  126.    
  127.     public void setView(View view)
  128.     {
  129.         mView = view;
  130.         if (view != null)
  131.         {
  132.             view.setOnGenericMotionListener(this);
  133.             view.setOnKeyListener(this);
  134.         }
  135.     }
  136.    
  137.     public boolean onGenericMotion(View view, MotionEvent event)
  138.     {
  139.         boolean success = false;
  140.  
  141.         SensorData sensorData = sensors.get(inputDevice.getId());
  142.        
  143.         if (!initialized || !loaded)
  144.         {
  145.             return view.onGenericMotionEvent(event);
  146.         }
  147.        
  148.         // Check that the event came from a joystick since a generic motion event
  149.         // could be almost anything.
  150.         if ((event.getSource() & InputDevice.SOURCE_GAMEPAD) != 0
  151.                 && event.getAction() == MotionEvent.ACTION_MOVE) {
  152.             // Cache the most recently obtained device information.
  153.             // The device information may change over time but it can be
  154.             // somewhat expensive to query.
  155.             if (inputDevice == null || inputDevice.getId() != event.getDeviceId()) {
  156.                 inputDevice = event.getDevice();
  157.                 // It's possible for the device id to be invalid.
  158.                 // In that case, getDevice() will return null.
  159.                 if (inputDevice == null) {
  160.                     return false;
  161.                 }
  162.             }
  163.  
  164.             // Process all historical movement samples in the batch.
  165.             final int historySize = event.getHistorySize();
  166.             for (int i = 0; i < historySize; i++) {
  167.                 processJoystickInput(event, i, sensorData);
  168.             }
  169.  
  170.             // Process the current movement sample in the batch.
  171.             processJoystickInput(event, -1, sensorData);
  172.             return true;
  173.         }
  174.         return true;
  175.     }
  176.    
  177.     private void processJoystickInput(MotionEvent event, int historyPos, SensorData sensorData)
  178.     {
  179.  
  180.         // Get joystick position.
  181.         // Many game pads with two joysticks report the position of the second joystick
  182.         // using the Z and RZ axes so we also handle those.
  183.         // In a real game, we would allow the user to configure the axes manually.
  184.         float x = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_X, historyPos);
  185.         if (x == 0) {
  186.             x = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_HAT_X, historyPos);
  187.         }
  188.         if (x == 0) {
  189.             x = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_Z, historyPos);
  190.         }
  191.  
  192.         float y = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_Y, historyPos);
  193.         if (y == 0) {
  194.             y = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_HAT_Y, historyPos);
  195.         }
  196.         if (y == 0) {
  197.             y = getCenteredAxis(event, inputDevice, MotionEvent.AXIS_RZ, historyPos);
  198.         }    
  199.  
  200.         if (sensorData != null && sensorData.enabled)
  201.         {
  202.  
  203.             for (int i=0; i<sensorData.lastValues.length; i++)
  204.             {
  205.                 sensorData.lastValues[i] = event.getAxisValue(i);
  206.             }
  207.  
  208.             if (sensorData != null && sensorData.axes.size() > 0)
  209.             {
  210.                 AndroidJoystickAxis axis;
  211.                 for (int i=0; i<event.getHistorySize(); i++)
  212.                 {
  213.                     axis = sensorData.axes.get(i);
  214.                     if (axis != null) {
  215.                         axis.setCurRawValue(event.getAxisValue(i));
  216.                         if (!sensorData.haveData) {
  217.                             sensorData.haveData = true;
  218.                         } else {
  219.                             synchronized (eventQueue){
  220.                                 if (axis.isChanged()) {
  221.                                     eventQueue.add(new JoyAxisEvent(axis, axis.getJoystickAxisValue()));
  222.                                 }
  223.                             }
  224.                         }
  225.                     }
  226.                 }
  227.             } else if (sensorData != null)
  228.             {
  229.                 if (!sensorData.haveData) {
  230.                     sensorData.haveData = true;
  231.                 }
  232.             }
  233.  
  234.        
  235.         }
  236.     }
  237.  
  238.     private static float getCenteredAxis(MotionEvent event, InputDevice device,
  239.             int axis, int historyPos) {
  240.         final InputDevice.MotionRange range = device.getMotionRange(axis, event.getSource());
  241.         if (range != null) {
  242.             final float flat = range.getFlat();
  243.             final float value = historyPos < 0 ? event.getAxisValue(axis)
  244.                     : event.getHistoricalAxisValue(axis, historyPos);
  245.  
  246.             // Ignore axis values that are within the 'flat' region of the joystick axis center.
  247.             // A joystick at rest does not always report an absolute position of (0,0).
  248.             if (Math.abs(value) > flat) {
  249.                 return value;
  250.             }
  251.         }
  252.         return 0;
  253.     }
  254.  
  255.     public boolean onKey(View view, int i, KeyEvent ke)
  256.     {
  257.         int firstButton = 0;
  258.         SensorData sensorData = sensors.get(inputDevice.getId());
  259.        
  260.         AndroidJoystickButton button = sensorData.buttons.get(firstButton);
  261.        
  262.         synchronized (buttoneventQueue)
  263.         {
  264.             if(ke.getAction() == KeyEvent.ACTION_DOWN)
  265.             {
  266.                 button.setPressed(true);
  267.                 buttoneventQueue.add(new JoyButtonEvent(button, button.isPressed()));
  268.             }
  269.             else if(ke.getAction() == KeyEvent.ACTION_UP)
  270.             {
  271.                 button.setPressed(false);
  272.                 buttoneventQueue.add(new JoyButtonEvent(button, button.isPressed()));
  273.             }
  274.         }
  275.  
  276.         return true;
  277.     }
  278.    
  279.     /**
  280.      * Internal class to enclose data for each sensor.
  281.      */
  282.     private class SensorData
  283.     {
  284.         int androidSensorType = -1;
  285.         int androidSensorSpeed = SensorManager.SENSOR_DELAY_GAME;
  286.         InputDevice myinputDevice = null;
  287.         int sensorAccuracy = 0;
  288.         float[] lastValues;
  289.         final Object valuesLock = new Object();
  290.         ArrayList<AndroidJoystickAxis> axes = new ArrayList<AndroidJoystickAxis>();
  291.         ArrayList<AndroidJoystickButton> buttons = new ArrayList<AndroidJoystickButton>();
  292.         boolean enabled = false;
  293.         boolean haveData = false;
  294.  
  295.         public SensorData(int androidSensorType, InputDevice inputDevice) {
  296.             this.androidSensorType = androidSensorType;
  297.             this.myinputDevice = inputDevice;
  298.         }
  299.  
  300.     }
  301.  
  302.     private void initSensorManager() {
  303.         this.activity = JmeAndroidSystem.getActivity();
  304.         // Get instance of Vibrator from current Context
  305.         vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
  306.         if (vibrator == null) {
  307.             logger.log(Level.FINE, "Vibrator Service not found.");
  308.         }
  309.     }
  310.  
  311.     /**
  312.      * Pauses the sensors to save battery life if the sensors are not needed.
  313.      * Used to pause sensors when the activity pauses
  314.      */
  315.     public void pauseSensors()
  316.     {
  317.         if (vibrator != null && vibratorActive) {
  318.             vibrator.cancel();
  319.         }
  320.     }
  321.  
  322.     /**
  323.      * Resumes the sensors.
  324.      * Used to resume sensors when the activity comes to the top of the stack
  325.      */
  326.     public void resumeSensors()
  327.     {
  328.  
  329.     }
  330.  
  331.     /*
  332.      * Allows the orientation data to be rotated based on the current device
  333.      * rotation.  This keeps the data aligned with the game when the user
  334.      * rotates the device during game play.
  335.      *
  336.      * Android remapCoordinateSystem from the Android docs
  337.      * remapCoordinateSystem(float[] inR, int X, int Y, float[] outR)
  338.      *
  339.      * @param   inR   the rotation matrix to be transformed. Usually it is the matrix
  340.      *          returned by getRotationMatrix(float[], float[], float[], float[]).
  341.      *
  342.      * @param   outR  the transformed rotation matrix. inR and outR can be the same
  343.      *          array, but it is not recommended for performance reason.
  344.      *
  345.      * X     defines on which world (Earth) axis and direction the X axis of the device is mapped.
  346.      * Y     defines on which world (Earth) axis and direction the Y axis of the device is mapped.
  347.      *
  348.      * @return True if successful
  349.      */
  350.     private boolean remapCoordinates(float[] inR, float[] outR) {
  351.         int xDir = SensorManager.AXIS_X;
  352.         int yDir = SensorManager.AXIS_Y;
  353.         int curRotation = getScreenRotation();
  354.         if (lastRotation != curRotation) {
  355.             logger.log(Level.FINE, "Device Rotation changed to: {0}", curRotation);
  356.         }
  357.         lastRotation = curRotation;
  358.  
  359. //        logger.log(Level.FINE, "Screen Rotation: {0}", getScreenRotation());
  360.         switch (getScreenRotation()) {
  361.             // device natural position
  362.             case Surface.ROTATION_0:
  363.                 xDir = SensorManager.AXIS_X;
  364.                 yDir = SensorManager.AXIS_Y;
  365.                 break;
  366.             // device rotated 90 deg counterclockwise
  367.             case Surface.ROTATION_90:
  368.                 xDir = SensorManager.AXIS_Y;
  369.                 yDir = SensorManager.AXIS_MINUS_X;
  370.                 break;
  371.             // device rotated 180 deg counterclockwise
  372.             case Surface.ROTATION_180:
  373.                 xDir = SensorManager.AXIS_MINUS_X;
  374.                 yDir = SensorManager.AXIS_MINUS_Y;
  375.                 break;
  376.             // device rotated 270 deg counterclockwise
  377.             case Surface.ROTATION_270:
  378.                 xDir = SensorManager.AXIS_MINUS_Y;
  379.                 yDir = SensorManager.AXIS_X;
  380.                 break;
  381.             default:
  382.                 break;
  383.         }
  384.         return SensorManager.remapCoordinateSystem(inR, xDir, yDir, outR);
  385.     }
  386.  
  387.     /**
  388.      * Returns the current device rotation.
  389.      * Surface.ROTATION_0 = device in natural default rotation
  390.      * Surface.ROTATION_90 = device in rotated 90deg counterclockwise
  391.      * Surface.ROTATION_180 = device in rotated 180deg counterclockwise
  392.      * Surface.ROTATION_270 = device in rotated 270deg counterclockwise
  393.      *
  394.      * When the Manifest locks the orientation, this value will not change during
  395.      * gametime, but if the orientation of the screen is based off the sensor,
  396.      * this value will change as the device is rotated.
  397.      * @return Current device rotation amount
  398.      */
  399.     private int getScreenRotation() {
  400.         return activity.getWindowManager().getDefaultDisplay().getRotation();
  401.     }
  402.  
  403.     // Start of JoyInput methods
  404.  
  405.     public void setJoyRumble(int joyId, float amount) {
  406.         // convert amount to pulses since Android doesn't allow intensity
  407.         if (vibrator != null) {
  408.             final long rumbleOnDur = (long)(amount * maxRumbleTime); // ms to pulse vibration on
  409.             final long rumbleOffDur = maxRumbleTime - rumbleOnDur; // ms to delay between pulses
  410.             final long[] rumblePattern = {
  411.                 0, // start immediately
  412.                 rumbleOnDur, // time to leave vibration on
  413.                 rumbleOffDur // time to delay between vibrations
  414.             };
  415.             final int rumbleRepeatFrom = 0; // index into rumble pattern to repeat from
  416.  
  417.             logger.log(Level.FINE, "Rumble amount: {0}, rumbleOnDur: {1}, rumbleOffDur: {2}",
  418.                     new Object[]{amount, rumbleOnDur, rumbleOffDur});
  419.  
  420.             if (rumbleOnDur > 0) {
  421.                 vibrator.vibrate(rumblePattern, rumbleRepeatFrom);
  422.                 vibratorActive = true;
  423.             } else {
  424.                 vibrator.cancel();
  425.                 vibratorActive = false;
  426.             }
  427.         }
  428.  
  429.     }
  430.  
  431.     public Joystick[] loadJoysticks(InputManager inputManager) {
  432.         this.inputManager = inputManager;
  433.        
  434.         androidInputManager = (android.hardware.input.InputManager) JmeAndroidSystem.getActivity().getSystemService(Context.INPUT_SERVICE);
  435.        
  436.         devicesIDs = new int[androidInputManager.getInputDeviceIds().length];
  437.        
  438.         System.arraycopy(androidInputManager.getInputDeviceIds(), 0, devicesIDs, 0, androidInputManager.getInputDeviceIds().length);    
  439.        
  440.        
  441.         for(int index = 0; index < devicesIDs.length; index++)
  442.         {
  443.             inputDevice = androidInputManager.getInputDevice(devicesIDs[index]);
  444.             System.out.println("Input Device Name: " + inputDevice.getName());
  445.         }
  446.        
  447.        
  448.         initSensorManager();
  449.         setView(mView);
  450.        
  451.         int myButtonNumber = 96;
  452.  
  453.         SensorData sensorData;
  454.         List<Joystick> list = new ArrayList<Joystick>();
  455.         AndroidJoystick joystick;
  456.         AndroidJoystickAxis axis;
  457.         AndroidJoystickButton button;
  458.  
  459.         joystick = new AndroidJoystick(inputManager,
  460.                                     this,
  461.                                     list.size(),
  462.                                     "AndroidSensorsJoystick");
  463.         list.add(joystick);
  464.  
  465.         // manually create orientation sensor data since orientation is not a physical sensor
  466.         sensorData = new SensorData(InputDevice.SOURCE_GAMEPAD, inputDevice);
  467.  
  468.         //sensorData.sensor = sensorManager.getDefaultSensor(sensorType);
  469.         sensorData.enabled = true;
  470.  
  471.         if (sensorData != null) {
  472.             sensorData.lastValues = new float[2];
  473.             sensors.put(inputDevice.getId(), sensorData);      
  474.            
  475.             axis = joystick.addAxis(SensorJoystickAxis.ORIENTATION_X, SensorJoystickAxis.ORIENTATION_X, joystick.getAxisCount(), FastMath.HALF_PI);
  476.             joystick.setYAxis(axis); // joystick y axis = rotation around device x axis
  477.             sensorData.axes.add(axis);
  478.            
  479.             button = joystick.addButton(JoystickButton.BUTTON_0, JoystickButton.BUTTON_0, myButtonNumber);
  480.             joystick.setButton(button);
  481.             sensorData.buttons.add(button);
  482.            
  483.             axis = joystick.addAxis(SensorJoystickAxis.ORIENTATION_Y, SensorJoystickAxis.ORIENTATION_Y, joystick.getAxisCount(), FastMath.HALF_PI);
  484.             joystick.setXAxis(axis); // joystick x axis = rotation around device y axis
  485.             sensorData.axes.add(axis);
  486.         }
  487.  
  488.         joysticks = list.toArray( new AndroidJoystick[list.size()] );
  489.         loaded = true;
  490.         return joysticks;
  491.     }
  492.  
  493.     public void initialize()
  494.     {
  495.         initialized = true;
  496.         loaded = false;
  497.     }
  498.  
  499.     public void update() {
  500.         if (!loaded) {
  501.             return;
  502.         }
  503.         synchronized (eventQueue){
  504.             // flush events to listener
  505.             if (listener != null && eventQueue.size() > 0) {
  506.                 for (int i = 0; i < eventQueue.size(); i++){
  507.                     listener.onJoyAxisEvent(eventQueue.get(i));
  508.                 }
  509.                 eventQueue.clear();
  510.             }
  511.         }
  512.        
  513.         synchronized (buttoneventQueue)
  514.         {
  515.             // flush events to listener
  516.             if (listener != null && buttoneventQueue.size() > 0) {
  517.                 for (int i = 0; i < buttoneventQueue.size(); i++){
  518.                     listener.onJoyButtonEvent(buttoneventQueue.get(i));
  519.                 }
  520.                 buttoneventQueue.clear();
  521.             }
  522.         }
  523.     }
  524.  
  525.     public void destroy() {
  526.         logger.log(Level.FINE, "Doing Destroy.");
  527.         pauseSensors();
  528.         sensors.clear();
  529.         eventQueue.clear();
  530.         buttoneventQueue.clear();
  531.         initialized = false;
  532.         loaded = false;
  533.         joysticks = null;
  534.         vibrator = null;
  535.         activity = null;
  536.     }
  537.  
  538.     public boolean isInitialized() {
  539.         return initialized;
  540.     }
  541.  
  542.     public void setInputListener(RawInputListener listener) {
  543.         this.listener = listener;
  544.     }
  545.  
  546.     public long getInputTimeNanos() {
  547.         return System.nanoTime();
  548.     }
  549.  
  550.     // End of JoyInput methods
  551.  
  552.     protected class AndroidJoystick extends AbstractJoystick {
  553.         private JoystickAxis nullAxis;
  554.         private JoystickAxis xAxis;
  555.         private JoystickAxis yAxis;
  556.         private JoystickAxis povX;
  557.         private JoystickAxis povY;
  558.         private JoystickButton button;
  559.        
  560.         private Map<Integer, JoystickButton> buttonIndex = new HashMap<Integer, JoystickButton>();
  561.  
  562.         public AndroidJoystick( InputManager inputManager, JoyInput joyInput,
  563.                                 int joyId, String name){
  564.  
  565.             super( inputManager, joyInput, joyId, name );
  566.  
  567.             this.nullAxis = new DefaultJoystickAxis( getInputManager(), this, -1,
  568.                                                      "Null", "null", false, false, 0 );
  569.             this.xAxis = nullAxis;
  570.             this.yAxis = nullAxis;
  571.             this.povX = nullAxis;
  572.             this.povY = nullAxis;
  573.  
  574.         }
  575.  
  576.         protected AndroidJoystickAxis addAxis(String axisName, String logicalName, int axisNum, float maxRawValue) {
  577.             AndroidJoystickAxis axis;
  578.  
  579.             axis = new AndroidJoystickAxis(
  580.                     inputManager,               // InputManager (InputManager)
  581.                     this,                       // parent Joystick (Joystick)
  582.                     axisNum,                    // Axis Index (int)
  583.                     axisName,                   // Axis Name (String)
  584.                     logicalName,                // Logical ID (String)
  585.                     true,                       // isAnalog (boolean)
  586.                     false,                      // isRelative (boolean)
  587.                     0.01f,                      // Axis Deadzone (float)
  588.                     maxRawValue);               // Axis Max Raw Value (float)
  589.  
  590.             super.addAxis(axis);
  591.  
  592.             return axis;
  593.         }
  594.        
  595.         protected AndroidJoystickButton addButton(String buttonName, String logicalName, int buttonNum) {
  596.             AndroidJoystickButton mybutton;
  597.  
  598.             mybutton = new AndroidJoystickButton(
  599.                     inputManager,               // InputManager (InputManager)
  600.                     this,                       // parent Joystick (Joystick)
  601.                     buttonNum,                    // Axis Index (int)
  602.                     buttonName,                   // Axis Name (String)
  603.                     logicalName);                // Logical ID (String)
  604.  
  605.             super.addButton(mybutton);
  606.  
  607.             return mybutton;
  608.         }
  609.        
  610.         protected void setButton(JoystickButton bttn)
  611.         {
  612.             button = bttn;            
  613.         }        
  614.  
  615.         protected void setXAxis(JoystickAxis axis) {
  616.             xAxis = axis;
  617.         }
  618.         protected void setYAxis(JoystickAxis axis) {
  619.             yAxis = axis;
  620.         }
  621.  
  622.         @Override
  623.         public JoystickAxis getXAxis() {
  624.             return xAxis;
  625.         }
  626.  
  627.         @Override
  628.         public JoystickAxis getYAxis() {
  629.             return yAxis;
  630.         }
  631.  
  632.         @Override
  633.         public JoystickAxis getPovXAxis() {
  634.             return povX;
  635.         }
  636.  
  637.         @Override
  638.         public JoystickAxis getPovYAxis() {
  639.             return povY;
  640.         }
  641.  
  642.     }
  643.  
  644.     public class AndroidJoystickAxis extends DefaultJoystickAxis implements SensorJoystickAxis {
  645.         float zeroRawValue = 0f;
  646.         float curRawValue = 0f;
  647.         float lastRawValue = 0f;
  648.         boolean hasChanged = false;
  649.         float maxRawValue = FastMath.HALF_PI;
  650.         boolean enabled = true;
  651.  
  652.         public AndroidJoystickAxis(InputManager inputManager, Joystick parent,
  653.                            int axisIndex, String name, String logicalId,
  654.                            boolean isAnalog, boolean isRelative, float deadZone,
  655.                            float maxRawValue) {
  656.             super(inputManager, parent, axisIndex, name, logicalId, isAnalog, isRelative, deadZone);
  657.  
  658.             this.maxRawValue = maxRawValue;
  659.         }
  660.  
  661.         public float getMaxRawValue() {
  662.             return maxRawValue;
  663.         }
  664.  
  665.         public void setMaxRawValue(float maxRawValue) {
  666.             this.maxRawValue = maxRawValue;
  667.         }
  668.  
  669.         protected float getLastRawValue() {
  670.             return lastRawValue;
  671.         }
  672.         protected void setCurRawValue(float rawValue) {
  673.             this.curRawValue = rawValue;
  674.             if (Math.abs(curRawValue - lastRawValue) > getDeadZone()) {
  675.                 hasChanged = true;
  676.                 lastRawValue = curRawValue;
  677.             } else {
  678.                 hasChanged = false;
  679.             }
  680.         }
  681.  
  682.         protected float getJoystickAxisValue() {
  683.             return (lastRawValue-zeroRawValue) / maxRawValue;
  684.         }
  685.  
  686.         protected boolean isChanged() {
  687.             return hasChanged;
  688.         }
  689.  
  690.         public void calibrateCenter() {
  691.             zeroRawValue = lastRawValue;
  692.             logger.log(Level.FINE, "Calibrating axis {0} to {1}",
  693.                     new Object[]{getName(), zeroRawValue});
  694.         }
  695.  
  696.     }
  697.    
  698.     public class AndroidJoystickButton extends DefaultJoystickButton
  699.     {
  700.         int keyCode = -1;
  701.         boolean pressed = false;
  702.         boolean hasChanged = false;
  703.  
  704.         public AndroidJoystickButton(InputManager inputManager, Joystick parent,
  705.                 int buttonIndex, String name, String logicalId)
  706.         {
  707.             super(inputManager, parent, buttonIndex, name, logicalId);
  708.         }        
  709.  
  710.         protected boolean isChanged() {
  711.             return hasChanged;
  712.         }
  713.        
  714.         protected void setPressed (boolean pr)
  715.         {
  716.             pressed = pr;
  717.         }        
  718.        
  719.         protected boolean isPressed()
  720.         {
  721.             return pressed;
  722.         }        
  723.        
  724.         protected int getKeyCode()
  725.         {
  726.             return keyCode;
  727.         }      
  728.        
  729.         protected void setKeyCode(int kc)
  730.         {
  731.             keyCode = kc;
  732.         }  
  733.     }
  734. }
Advertisement
Add Comment
Please, Sign In to add comment