Search in sources :

Example 1 with Device

use of com.jme3.opencl.Device in project jmonkeyengine by jMonkeyEngine.

the class VRAppState method stateAttached.

@Override
public void stateAttached(AppStateManager stateManager) {
    //To change body of generated methods, choose Tools | Templates.
    super.stateAttached(stateManager);
    if (settings == null) {
        settings = new AppSettings(true);
        logger.config("Using default settings.");
    } else {
        logger.config("Using given settings.");
    }
    // Attach VR environment to the application
    if (!environment.isInitialized()) {
        environment.initialize();
    }
    if (environment.isInitialized()) {
        environment.atttach(this, stateManager.getApplication());
    } else {
        logger.severe("Cannot attach VR environment to the VR app state as its not initialized.");
    }
    GraphicsDevice defDev = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    if (environment.isInVR() && !environment.compositorAllowed()) {
        // "easy extended" mode
        // setup experimental JFrame on external device
        // first, find the VR device
        GraphicsDevice VRdev = null;
        GraphicsDevice[] devs = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
        // pick the display that isn't the default one
        for (GraphicsDevice gd : devs) {
            if (gd != defDev) {
                VRdev = gd;
                break;
            }
        }
        // did we get the VR device?
        if (VRdev != null) {
            // set properties for VR acceleration
            try {
                java.awt.DisplayMode useDM = null;
                int max = 0;
                for (java.awt.DisplayMode dm : VRdev.getDisplayModes()) {
                    int check = dm.getHeight() + dm.getWidth() + dm.getRefreshRate() + dm.getBitDepth();
                    if (check > max) {
                        max = check;
                        useDM = dm;
                    }
                }
                // create a window for the VR device
                settings.setWidth(useDM.getWidth());
                settings.setHeight(useDM.getHeight());
                settings.setBitsPerPixel(useDM.getBitDepth());
                settings.setFrequency(useDM.getRefreshRate());
                settings.setSwapBuffers(true);
                // allow vsync on this display
                settings.setVSync(true);
                stateManager.getApplication().setSettings(settings);
                logger.config("Updated underlying application settings.");
                // make sure we are in the right display mode
                if (VRdev.getDisplayMode().equals(useDM) == false) {
                    VRdev.setDisplayMode(useDM);
                }
                return;
            } catch (Exception e) {
                logger.log(Level.SEVERE, e.getMessage(), e);
            }
        } else {
            logger.config("Cannot access to external screen.");
        }
    } else {
        if (!environment.isInVR()) {
            logger.config("Cannot switch to VR mode (VR disabled by user).");
        } else if (!environment.compositorAllowed()) {
            logger.warning("Cannot switch to VR mode (VR not supported).");
        }
    }
    if (!environment.isInVR()) {
        //FIXME: Handling GLFW workaround on MacOS
        boolean macOs = false;
        if (macOs) {
            // GLFW workaround on macs
            settings.setFrequency(defDev.getDisplayMode().getRefreshRate());
            settings.setDepthBits(24);
            settings.setVSync(true);
            // try and read resolution from file in local dir
            File resfile = new File("resolution.txt");
            if (resfile.exists()) {
                try {
                    BufferedReader br = new BufferedReader(new FileReader(resfile));
                    settings.setWidth(Integer.parseInt(br.readLine()));
                    settings.setHeight(Integer.parseInt(br.readLine()));
                    try {
                        settings.setFullscreen(br.readLine().toLowerCase(Locale.ENGLISH).contains("full"));
                    } catch (Exception e) {
                        settings.setFullscreen(false);
                    }
                    br.close();
                } catch (Exception e) {
                    settings.setWidth(1280);
                    settings.setHeight(720);
                }
            } else {
                settings.setWidth(1280);
                settings.setHeight(720);
                settings.setFullscreen(false);
            }
            settings.setResizable(false);
        }
        settings.setSwapBuffers(true);
    } else {
        // use basic mirroring window, skip settings window
        settings.setSamples(1);
        settings.setWidth(xWin);
        settings.setHeight(yWin);
        settings.setBitsPerPixel(32);
        settings.setFrameRate(0);
        settings.setFrequency(environment.getVRHardware().getDisplayFrequency());
        settings.setFullscreen(false);
        // stop vsyncing on primary monitor!
        settings.setVSync(false);
        settings.setSwapBuffers(environment.isSwapBuffers());
    }
    // Updating application settings
    stateManager.getApplication().setSettings(settings);
    logger.config("Updated underlying application settings.");
}
Also used : GraphicsDevice(java.awt.GraphicsDevice) AppSettings(com.jme3.system.AppSettings) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) File(java.io.File)

Example 2 with Device

use of com.jme3.opencl.Device in project jmonkeyengine by jMonkeyEngine.

the class OGLESContext method createView.

/**
     * <code>createView</code> creates the GLSurfaceView that the renderer will
     * draw to. <p> The result GLSurfaceView will receive input events and
     * forward them to the Application. Any rendering will be done into the
     * GLSurfaceView. Only one GLSurfaceView can be created at this time. The
     * given configType specifies how to determine the display configuration.
     *
     * @return GLSurfaceView The newly created view
     */
public GLSurfaceView createView(Context context) {
    // NOTE: We assume all ICS devices have OpenGL ES 2.0.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // below 4.0, check OpenGL ES 2.0 support.
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ConfigurationInfo info = am.getDeviceConfigurationInfo();
        if (info.reqGlEsVersion < 0x20000) {
            throw new UnsupportedOperationException("OpenGL ES 2.0 is not supported on this device");
        }
    } else if (Build.VERSION.SDK_INT < 9) {
        throw new UnsupportedOperationException("jME3 requires Android 2.3 or later");
    }
    // Start to set up the view
    GLSurfaceView view = new GLSurfaceView(context);
    logger.log(Level.INFO, "Android Build Version: {0}", Build.VERSION.SDK_INT);
    if (androidInput == null) {
        if (Build.VERSION.SDK_INT >= 14) {
            androidInput = new AndroidInputHandler14();
        } else if (Build.VERSION.SDK_INT >= 9) {
            androidInput = new AndroidInputHandler();
        }
    }
    androidInput.setView(view);
    androidInput.loadSettings(settings);
    // setEGLContextClientVersion must be set before calling setRenderer
    // this means it cannot be set in AndroidConfigChooser (too late)
    view.setEGLContextClientVersion(2);
    view.setFocusableInTouchMode(true);
    view.setFocusable(true);
    // setFormat must be set before AndroidConfigChooser is called by the surfaceview.
    // if setFormat is called after ConfigChooser is called, then execution
    // stops at the setFormat call without a crash.
    // We look at the user setting for alpha bits and set the surfaceview
    // PixelFormat to either Opaque, Transparent, or Translucent.
    // ConfigChooser will do it's best to honor the alpha requested by the user
    // For best rendering performance, use Opaque (alpha bits = 0).
    int curAlphaBits = settings.getAlphaBits();
    logger.log(Level.FINE, "curAlphaBits: {0}", curAlphaBits);
    if (curAlphaBits >= 8) {
        logger.log(Level.FINE, "Pixel Format: TRANSLUCENT");
        view.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        view.setZOrderOnTop(true);
    } else if (curAlphaBits >= 1) {
        logger.log(Level.FINE, "Pixel Format: TRANSPARENT");
        view.getHolder().setFormat(PixelFormat.TRANSPARENT);
    } else {
        logger.log(Level.FINE, "Pixel Format: OPAQUE");
        view.getHolder().setFormat(PixelFormat.OPAQUE);
    }
    AndroidConfigChooser configChooser = new AndroidConfigChooser(settings);
    view.setEGLConfigChooser(configChooser);
    view.setRenderer(this);
    // reloading all the OpenGL objects.
    if (Build.VERSION.SDK_INT >= 11) {
        view.setPreserveEGLContextOnPause(true);
    }
    return view;
}
Also used : AndroidInputHandler(com.jme3.input.android.AndroidInputHandler) AndroidInputHandler14(com.jme3.input.android.AndroidInputHandler14) ActivityManager(android.app.ActivityManager) GLSurfaceView(android.opengl.GLSurfaceView) ConfigurationInfo(android.content.pm.ConfigurationInfo)

Example 3 with Device

use of com.jme3.opencl.Device in project jmonkeyengine by jMonkeyEngine.

the class AndroidJoystickJoyInput14 method loadJoysticks.

public List<Joystick> loadJoysticks(int joyId, InputManager inputManager) {
    logger.log(Level.INFO, "loading Joystick devices");
    ArrayList<Joystick> joysticks = new ArrayList<Joystick>();
    joysticks.clear();
    joystickIndex.clear();
    ArrayList gameControllerDeviceIds = new ArrayList();
    int[] deviceIds = InputDevice.getDeviceIds();
    for (int deviceId : deviceIds) {
        InputDevice dev = InputDevice.getDevice(deviceId);
        int sources = dev.getSources();
        logger.log(Level.FINE, "deviceId[{0}] sources: {1}", new Object[] { deviceId, sources });
        // Verify that the device has gamepad buttons, control sticks, or both.
        if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) || ((sources & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK)) {
            // This device is a game controller. Store its device ID.
            if (!gameControllerDeviceIds.contains(deviceId)) {
                gameControllerDeviceIds.add(deviceId);
                logger.log(Level.FINE, "Attempting to create joystick for device: {0}", dev);
                // Create an AndroidJoystick and store the InputDevice so we
                // can later correspond the input from the InputDevice to the
                // appropriate jME Joystick event
                AndroidJoystick joystick = new AndroidJoystick(inputManager, joyInput, dev, joyId + joysticks.size(), dev.getName());
                joystickIndex.put(deviceId, joystick);
                joysticks.add(joystick);
                // Each analog input is reported as a MotionRange
                // The axis number corresponds to the type of axis
                // The AndroidJoystick.addAxis(MotionRange) converts the axis
                // type reported by Android into the jME Joystick axis
                List<MotionRange> motionRanges = dev.getMotionRanges();
                for (MotionRange motionRange : motionRanges) {
                    logger.log(Level.INFO, "motion range: {0}", motionRange.toString());
                    logger.log(Level.INFO, "axis: {0}", motionRange.getAxis());
                    JoystickAxis axis = joystick.addAxis(motionRange);
                    logger.log(Level.INFO, "added axis: {0}", axis);
                }
                // device, but I haven't found a better way yet.
                for (int keyCode : AndroidGamepadButtons) {
                    logger.log(Level.INFO, "button[{0}]: {1}", new Object[] { keyCode, KeyCharacterMap.deviceHasKey(keyCode) });
                    if (KeyCharacterMap.deviceHasKey(keyCode)) {
                        // add button even though we aren't sure if the button
                        // actually exists on this InputDevice
                        logger.log(Level.INFO, "button[{0}] exists somewhere", keyCode);
                        JoystickButton button = joystick.addButton(keyCode);
                        logger.log(Level.INFO, "added button: {0}", button);
                    }
                }
            }
        }
    }
    loaded = true;
    return joysticks;
}
Also used : DefaultJoystickButton(com.jme3.input.DefaultJoystickButton) JoystickButton(com.jme3.input.JoystickButton) InputDevice(android.view.InputDevice) AbstractJoystick(com.jme3.input.AbstractJoystick) Joystick(com.jme3.input.Joystick) ArrayList(java.util.ArrayList) JoystickAxis(com.jme3.input.JoystickAxis) DefaultJoystickAxis(com.jme3.input.DefaultJoystickAxis) MotionRange(android.view.InputDevice.MotionRange)

Example 4 with Device

use of com.jme3.opencl.Device in project jmonkeyengine by jMonkeyEngine.

the class AndroidSensorJoyInput method updateOrientation.

/**
     * Calculates the device orientation based off the data recieved from the
     * Acceleration Sensor and Mangetic Field sensor
     * Values are returned relative to the Earth.
     *
     * From the Android Doc
     *
     * Computes the device's orientation based on the rotation matrix. When it returns, the array values is filled with the result:
     *  values[0]: azimuth, rotation around the Z axis.
     *  values[1]: pitch, rotation around the X axis.
     *  values[2]: roll, rotation around the Y axis.
     *
     * The reference coordinate-system used is different from the world
     * coordinate-system defined for the rotation matrix:
     *  X is defined as the vector product Y.Z (It is tangential to the ground at the device's current location and roughly points West).
     *  Y is tangential to the ground at the device's current location and points towards the magnetic North Pole.
     *  Z points towards the center of the Earth and is perpendicular to the ground.
     *
     * @return True if Orientation was calculated
     */
private boolean updateOrientation() {
    SensorData sensorData;
    AndroidSensorJoystickAxis axis;
    final float[] curInclinationMat = new float[16];
    final float[] curRotationMat = new float[16];
    final float[] rotatedRotationMat = new float[16];
    final float[] accValues = new float[3];
    final float[] magValues = new float[3];
    final float[] orderedOrientation = new float[3];
    // if the Gravity Sensor is available, use it for orientation, if not
    // use the accelerometer
    // NOTE: Seemed to work worse, so just using accelerometer
    //        sensorData = sensors.get(Sensor.TYPE_GRAVITY);
    //        if (sensorData == null) {
    sensorData = sensors.get(Sensor.TYPE_ACCELEROMETER);
    if (sensorData == null || !sensorData.enabled || !sensorData.haveData) {
        return false;
    }
    if (sensorData.sensorAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
        return false;
    }
    synchronized (sensorData.valuesLock) {
        accValues[0] = sensorData.lastValues[0];
        accValues[1] = sensorData.lastValues[1];
        accValues[2] = sensorData.lastValues[2];
    }
    sensorData = sensors.get(Sensor.TYPE_MAGNETIC_FIELD);
    if (sensorData == null || !sensorData.enabled || !sensorData.haveData) {
        return false;
    }
    if (sensorData.sensorAccuracy == SensorManager.SENSOR_STATUS_UNRELIABLE) {
        return false;
    }
    synchronized (sensorData.valuesLock) {
        magValues[0] = sensorData.lastValues[0];
        magValues[1] = sensorData.lastValues[1];
        magValues[2] = sensorData.lastValues[2];
    }
    if (SensorManager.getRotationMatrix(curRotationMat, curInclinationMat, accValues, magValues)) {
        final float[] orientValues = new float[3];
        if (remapCoordinates(curRotationMat, rotatedRotationMat)) {
            SensorManager.getOrientation(rotatedRotationMat, orientValues);
            //                logger.log(Level.FINE, "Orientation Values: {0}, {1}, {2}",
            //                        new Object[]{orientValues[0], orientValues[1], orientValues[2]});
            // need to reorder to make it x, y, z order instead of z, x, y order
            orderedOrientation[0] = orientValues[1];
            orderedOrientation[1] = orientValues[2];
            orderedOrientation[2] = orientValues[0];
            sensorData = sensors.get(Sensor.TYPE_ORIENTATION);
            if (sensorData != null && sensorData.axes.size() > 0) {
                for (int i = 0; i < orderedOrientation.length; i++) {
                    axis = sensorData.axes.get(i);
                    if (axis != null) {
                        axis.setCurRawValue(orderedOrientation[i]);
                        if (!sensorData.haveData) {
                            sensorData.haveData = true;
                        } else {
                            if (axis.isChanged()) {
                                joyInput.addEvent(new JoyAxisEvent(axis, axis.getJoystickAxisValue()));
                            }
                        }
                    }
                }
            } else if (sensorData != null) {
                if (!sensorData.haveData) {
                    sensorData.haveData = true;
                }
            }
            return true;
        } else {
            logger.log(Level.FINE, "remapCoordinateSystem failed");
        }
    } else {
        logger.log(Level.FINE, "getRotationMatrix returned false");
    }
    return false;
}
Also used : JoyAxisEvent(com.jme3.input.event.JoyAxisEvent)

Example 5 with Device

use of com.jme3.opencl.Device in project jmonkeyengine by jMonkeyEngine.

the class AndroidHarnessFragment method onCreate.

/**
     * This Fragment uses setRetainInstance(true) so the onCreate method will only
     * be called once. During device configuration changes, the instance of
     * this Fragment will be reused in the new Activity.  This method should not
     * contain any View related objects.  They are created and destroyed by
     * other methods.  View related objects should not be reused, but rather
     * created and destroyed along with the Activity.
     *
     * @param savedInstanceState
     */
@Override
public void onCreate(Bundle savedInstanceState) {
    initializeLogHandler();
    logger.fine("onCreate");
    super.onCreate(savedInstanceState);
    // Create Settings
    logger.log(Level.FINE, "Creating settings");
    AppSettings settings = new AppSettings(true);
    settings.setEmulateMouse(mouseEventsEnabled);
    settings.setEmulateMouseFlipAxis(mouseEventsInvertX, mouseEventsInvertY);
    settings.setUseJoysticks(joystickEventsEnabled);
    settings.setEmulateKeyboard(keyEventsEnabled);
    settings.setBitsPerPixel(eglBitsPerPixel);
    settings.setAlphaBits(eglAlphaBits);
    settings.setDepthBits(eglDepthBits);
    settings.setSamples(eglSamples);
    settings.setStencilBits(eglStencilBits);
    settings.setAudioRenderer(audioRendererType);
    settings.setFrameRate(frameRate);
    // Create application instance
    try {
        if (app == null) {
            @SuppressWarnings("unchecked") Class<? extends LegacyApplication> clazz = (Class<? extends LegacyApplication>) Class.forName(appClass);
            app = clazz.newInstance();
        }
        app.setSettings(settings);
        app.start();
    } catch (Exception ex) {
        handleError("Class " + appClass + " init failed", ex);
    }
    OGLESContext ctx = (OGLESContext) app.getContext();
    // AndroidHarness wraps the app as a SystemListener.
    ctx.setSystemListener(this);
    setRetainInstance(true);
}
Also used : AppSettings(com.jme3.system.AppSettings) OGLESContext(com.jme3.system.android.OGLESContext)

Aggregations

ArrayList (java.util.ArrayList)4 DefaultPlatformChooser (com.jme3.opencl.DefaultPlatformChooser)3 Device (com.jme3.opencl.Device)3 PlatformChooser (com.jme3.opencl.PlatformChooser)3 RendererException (com.jme3.renderer.RendererException)3 AppSettings (com.jme3.system.AppSettings)3 List (java.util.List)3 Joystick (com.jme3.input.Joystick)2 JoystickAxis (com.jme3.input.JoystickAxis)2 Material (com.jme3.material.Material)2 LwjglDevice (com.jme3.opencl.lwjgl.LwjglDevice)2 LwjglPlatform (com.jme3.opencl.lwjgl.LwjglPlatform)2 Geometry (com.jme3.scene.Geometry)2 Box (com.jme3.scene.shape.Box)2 GraphicsDevice (java.awt.GraphicsDevice)2 BufferedReader (java.io.BufferedReader)2 File (java.io.File)2 FileReader (java.io.FileReader)2 ActivityManager (android.app.ActivityManager)1 ConfigurationInfo (android.content.pm.ConfigurationInfo)1