Example usage for java.lang Math toDegrees

List of usage examples for java.lang Math toDegrees

Introduction

In this page you can find the example usage for java.lang Math toDegrees.

Prototype

public static double toDegrees(double angrad) 

Source Link

Document

Converts an angle measured in radians to an approximately equivalent angle measured in degrees.

Usage

From source file:uk.org.rivernile.edinburghbustracker.android.fragments.general.BusStopDetailsFragment.java

/**
 * Update the direction needle so that it is pointing towards the bus stop,
 * based on the device location and the direction it is facing.
 *//* w  ww.j a  v  a2 s .c  om*/
private void updateDirectionNeedle() {
    // We need values for location, the accelerometer and magnetometer to
    // continue.
    if (lastLocation == null || accelerometerValues == null || magnetometerValues == null) {
        // Make sure the needle isn't showing.
        txtDistance.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        recycleNeedleBitmapIfNotNull(null);

        return;
    }

    // Calculating the rotation matrix may fail, for example, if the device
    // is in freefall. In that case we cannot continue as the values will
    // be unreliable.
    if (!SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerValues, magnetometerValues)) {
        return;
    }

    // The screen rotation was obtained earlier.
    switch (screenRotation) {
    // There's lots of information about this elsewhere, but briefly;
    // The values from the sensors are in the device's coordinate system
    // which may be correct if the device is in its natural orientation,
    // but it needs to be remapped if the device is rotated.
    case Surface.ROTATION_0:
        SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z,
                rotationMatrix);
        break;
    case Surface.ROTATION_90:
        SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_Z, SensorManager.AXIS_MINUS_X,
                rotationMatrix);
        break;
    case Surface.ROTATION_180:
        SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_MINUS_X,
                SensorManager.AXIS_MINUS_Z, rotationMatrix);
        break;
    case Surface.ROTATION_270:
        SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_MINUS_Z, SensorManager.AXIS_X,
                rotationMatrix);
        break;
    }

    // Get the X, Y and Z orientations, which are in radians. Covert this
    // in to degrees East of North.
    SensorManager.getOrientation(rotationMatrix, headings);
    double heading = Math.toDegrees(headings[0]);

    // If there's a GeomagneticField value, then adjust the heading to take
    // this in to account.
    if (geoField != null) {
        heading -= geoField.getDeclination();
    }

    // The orientation is in the range of -180 to +180. Convert this in to
    // a range of 0 to 360.
    final float bearingTo = distance[1] < 0 ? distance[1] + 360 : distance[1];

    // This is the heading to the bus stop.
    heading = bearingTo - heading;

    // The above calculation may come out as a negative number again. Put
    // this back in to the range of 0 to 360.
    if (heading < 0) {
        heading += 360;
    }

    // This 'if' statement is required to prevent a crash during device
    // rotation. It ensured that the Fragment is still part of the Activity.
    if (isAdded()) {
        // Get the arrow bitmap from the resources.
        final Bitmap needleIn = BitmapFactory.decodeResource(getResources(), R.drawable.heading_arrow);
        // Get an identity matrix and rotate it by the required amount.
        final Matrix m = new Matrix();
        m.setRotate((float) heading % 360, (float) needleIn.getWidth() / 2, (float) needleIn.getHeight() / 2);
        // Apply the rotation matrix to the Bitmap, to create a new Bitmap.
        final Bitmap needleOut = Bitmap.createBitmap(needleIn, 0, 0, needleIn.getWidth(), needleIn.getHeight(),
                m, true);

        // Recycle the needle read in if it's not the same as the rotated
        // needle.
        if (needleIn != needleOut) {
            needleIn.recycle();
        }

        // This Bitmap needs to be converted to a Drawable type.
        final BitmapDrawable drawable = new BitmapDrawable(getResources(), needleOut);
        // Set the new needle to be on the right hand side of the TextView.
        txtDistance.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        recycleNeedleBitmapIfNotNull(needleOut);
    } else {
        // If the Fragment is not added to the Activity, then make sure
        // there's no needle.
        txtDistance.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        recycleNeedleBitmapIfNotNull(null);
    }
}

From source file:radu.pidroid.Controller.java

private void computeTiltAngle() {
    float[] mRotationMatrix = new float[9];
    float[] mOrientationMatrix = new float[3];

    ///* w w w .j  a va2 s.co m*/
    if (!SensorManager.getRotationMatrix(mRotationMatrix, null, mAccelerometerData, mGeomagneticData))
        return;
    else
        SensorManager.getOrientation(mRotationMatrix, mOrientationMatrix);

    //
    turnAngle = (int) Math.round(Math.toDegrees((double) mOrientationMatrix[1]) + 90);
}

From source file:com.grottworkshop.gwsswipelayout.SwipeLayout.java

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (!isEnabledInAdapterView() || !isEnabled())
        return true;

    if (!isSwipeEnabled())
        return super.onTouchEvent(event);

    int action = event.getActionMasked();
    ViewParent parent = getParent();// www . jav  a 2s .  c o  m

    gestureDetector.onTouchEvent(event);
    Status status = getOpenStatus();
    ViewGroup touching = null;
    if (status == Status.Close) {
        touching = getSurfaceView();
    } else if (status == Status.Open) {
        touching = getBottomView();
    }

    switch (action) {
    case MotionEvent.ACTION_DOWN:
        mDragHelper.processTouchEvent(event);
        parent.requestDisallowInterceptTouchEvent(true);

        sX = event.getRawX();
        sY = event.getRawY();

        if (touching != null)
            touching.setPressed(true);

        return true;
    case MotionEvent.ACTION_MOVE: {
        if (sX == -1 || sY == -1) {
            // Trick:
            // When in nested mode, we need to send a constructed ACTION_DOWN MotionEvent to mDragHelper, to help
            // it initialize itself.
            event.setAction(MotionEvent.ACTION_DOWN);
            mDragHelper.processTouchEvent(event);
            parent.requestDisallowInterceptTouchEvent(true);
            sX = event.getRawX();
            sY = event.getRawY();
            return true;
        }

        float distanceX = event.getRawX() - sX;
        float distanceY = event.getRawY() - sY;
        float angle = Math.abs(distanceY / distanceX);
        angle = (float) Math.toDegrees(Math.atan(angle));

        boolean doNothing = false;
        if (mDragEdge == DragEdge.Right) {
            boolean suitable = (status == Status.Open && distanceX > 0)
                    || (status == Status.Close && distanceX < 0);
            suitable = suitable || (status == Status.Middle);

            if (angle > 30 || !suitable) {
                doNothing = true;
            }
        }

        if (mDragEdge == DragEdge.Left) {
            boolean suitable = (status == Status.Open && distanceX < 0)
                    || (status == Status.Close && distanceX > 0);
            suitable = suitable || status == Status.Middle;

            if (angle > 30 || !suitable) {
                doNothing = true;
            }
        }

        if (mDragEdge == DragEdge.Top) {
            boolean suitable = (status == Status.Open && distanceY < 0)
                    || (status == Status.Close && distanceY > 0);
            suitable = suitable || status == Status.Middle;

            if (angle < 60 || !suitable) {
                doNothing = true;
            }
        }

        if (mDragEdge == DragEdge.Bottom) {
            boolean suitable = (status == Status.Open && distanceY > 0)
                    || (status == Status.Close && distanceY < 0);
            suitable = suitable || status == Status.Middle;

            if (angle < 60 || !suitable) {
                doNothing = true;
            }
        }

        if (doNothing) {
            parent.requestDisallowInterceptTouchEvent(false);
            return false;
        } else {
            if (touching != null) {
                touching.setPressed(false);
            }
            parent.requestDisallowInterceptTouchEvent(true);
            mDragHelper.processTouchEvent(event);
        }
        break;
    }
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL: {
        sX = -1;
        sY = -1;
        if (touching != null) {
            touching.setPressed(false);
        }
    }
    default:
        parent.requestDisallowInterceptTouchEvent(true);
        mDragHelper.processTouchEvent(event);
    }

    return true;
}

From source file:org.kalypsodeegree_impl.tools.GeometryUtilities.java

/**
 * Calculates the 'direction' of a vector in degrees. The degree value represents the angle between the vector and the
 * x-Axis in coordinate space./*from w ww  .  j  ava 2 s.  c o m*/
 * <p>
 * Orientation is anti.clockwise (i.e. positive).
 * </p>
 * 
 * @return The angle in degree or {@link Double#NaN} if the given vector has length 0.
 */
public static double directionFromVector(final double vx, final double vy) {
    final double length = Math.sqrt(vx * vx + vy * vy);
    if (length == 0.0) // double comparison problems?
        return Double.NaN;

    final double alpha = Math.acos(vx / length);

    if (vy < 0)
        return Math.toDegrees(2 * Math.PI - alpha);

    return Math.toDegrees(alpha);
}

From source file:com.spoiledmilk.ibikecph.navigation.SMRouteNavigationMapFragment.java

public void onSensorChanged(SensorEvent event) {

    if (event.sensor == mAccelerometer) {
        accValues.put(event.values);/*from w  w  w.j  a v a 2s.  co  m*/
        // System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
        mLastAccelerometerSet = true;
    } else if (event.sensor == mMagnetometer) {
        if (Math.sqrt(event.values[0] * event.values[0] + event.values[1] * event.values[1]
                + event.values[2] * event.values[2]) > SensorManager.MAGNETIC_FIELD_EARTH_MAX * 1.5) {
            return;
        }
        if (event.values.length < 3) {
            return;
        }
        magValues.put(event.values);
        // System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
        mLastMagnetometerSet = true;
    }

    if (mLastAccelerometerSet && mLastMagnetometerSet) {
        SensorManager.getRotationMatrix(mR, null, accValues.get(), magValues.get());
        // SensorManager.remapCoordinateSystem(mR, SensorManager.AXIS_X,
        // SensorManager.AXIS_Z, remapMatrix);
        SensorManager.getOrientation(mR, mOrientation); // remapMatrx
        if (SMLocationManager.getInstance().hasValidLocation()) {
            Location currentLoc = SMLocationManager.getInstance().getLastValidLocation();
            float azimuth = -(float) Math.toDegrees(mOrientation[0]);
            final GeomagneticField geoField = new GeomagneticField(
                    Double.valueOf(currentLoc.getLatitude()).floatValue(),
                    Double.valueOf(currentLoc.getLongitude()).floatValue(),
                    Double.valueOf(currentLoc.getAltitude()).floatValue(), System.currentTimeMillis());
            azimuth += geoField.getDeclination(); // converts magnetic north
            // into true north
            // LOG.d("azimuth = " + azimuth);
            compassOrientation = azimuth;// - bearing;
            // if (Math.abs(locationOverlay.compassOrientation - compassOrientation) > 5) {
            // locationOverlay.compassOrientation = compassOrientation;
            // mapView.invalidate();
            // }
            // }
            // }
        }
    }
}

From source file:org.bimserver.GeometryGenerator.java

/**
 * This function should return a transformation matrix (with translation and
 * rotation, no scaling) overlaying triangle V on U Assumed is that the
 * triangles are indeed the same and the order of the vertices is also the
 * same (shifts are not allowed) This function can probably be optimized for
 * speed and also the LOC can probably be reduced
 * /*from  ww  w .jav a2  s. c  om*/
 * @param originalV1
 * @param originalV2
 * @param originalV3
 * @param u1
 * @param u2
 * @param u3
 * @return
 */
private static float[] getTransformationMatrix(float[] originalV1, float[] originalV2, float[] originalV3,
        float[] u1, float[] u2, float[] u3, float maxDiff) {
    float[] v1 = copy(originalV1);
    float[] v2 = copy(originalV2);
    float[] v3 = copy(originalV3);
    u1 = copy(u1);
    u2 = copy(u2);
    u3 = copy(u3);

    float transX = u1[0] - v1[0];
    float transY = u1[1] - v1[1];
    float transZ = u1[2] - v1[2];

    float translation[] = new float[16];
    Matrix.setIdentityM(translation, 0);
    Matrix.translateM(translation, 0, u1[0], u1[1], u1[2]);

    float[] toZeroTranslation = new float[16];
    Matrix.setIdentityM(toZeroTranslation, 0);
    Matrix.translateM(toZeroTranslation, 0, -v1[0], -v1[1], -v1[2]);

    if (almostTheSame(v2[0] + transX, u2[0], maxDiff) && almostTheSame(v2[1] + transY, u2[1], maxDiff)
            && almostTheSame(v2[2] + transZ, u2[2], maxDiff) && almostTheSame(v3[0] + transX, u3[0], maxDiff)
            && almostTheSame(v3[1] + transY, u3[1], maxDiff) && almostTheSame(v3[2] + transZ, u3[2], maxDiff)) {
        // The other two points are already the same, to there was no
        // rotation
        return translation;
    }

    // Normalize both triangles to their first vertex
    subtract(u2, u1);
    subtract(u3, u1);
    subtract(u1, u1);

    subtract(v2, v1);
    subtract(v3, v1);
    subtract(v1, v1);

    float[] u2CrossV2 = Vector.crossProduct(u2, v2);
    float[] r2 = new float[16];
    Matrix.setIdentityM(r2, 0);
    float[] r2v2 = new float[4];
    if (!equalsAlmost(u2, v2, maxDiff)) {
        float u2InV2 = Vector.dot(u2, v2);
        float[] axis = u2CrossV2;
        if (axis[0] == 0 && axis[1] == 0 && axis[2] == 0) {
            axis = new float[] { u2[1], -u2[0], 0, 0 };
        }
        Matrix.rotateM(r2, 0, (float) Math.toDegrees(Math.atan2(Vector.length(u2CrossV2), u2InV2)), axis[0],
                axis[1], axis[2]);

        Matrix.multiplyMV(r2v2, 0, r2, 0, new float[] { v2[0], v2[1], v2[2], 1 }, 0);

        if (!equalsAlmost(r2v2, u2, maxDiff)) {
            Matrix.setIdentityM(r2, 0);
            Matrix.rotateM(r2, 0, -(float) Math.toDegrees(Math.atan2(Vector.length(u2CrossV2), u2InV2)),
                    axis[0], axis[1], axis[2]);
            Matrix.multiplyMV(r2v2, 0, r2, 0, new float[] { v2[0], v2[1], v2[2], 1 }, 0);
            if (!equalsAlmost(r2v2, u2, maxDiff)) {
                return null;
            }
        }
    } else {
        r2v2 = copy(v2);
    }

    float[] r2v3 = new float[4];
    Matrix.multiplyMV(r2v3, 0, r2, 0, new float[] { v3[0], v3[1], v3[2], 1 }, 0);

    float[] r3 = new float[16];
    Matrix.setIdentityM(r3, 0);

    float angleDegrees = (float) Math.toDegrees(getPlaneAngle(v1, r2v2, r2v3, u1, u2, u3));

    Matrix.rotateM(r3, 0, angleDegrees, r2v2[0], r2v2[1], r2v2[2]);

    float[] r3v3 = new float[4];
    Matrix.multiplyMV(r3v3, 0, r3, 0, new float[] { r2v3[0], r2v3[1], r2v3[2], 1 }, 0);

    float[] r2v1 = new float[4];
    Matrix.multiplyMV(r2v1, 0, r2, 0, new float[] { v1[0], v1[1], v1[2], 1 }, 0);

    float[] r3v1 = new float[4];
    Matrix.multiplyMV(r3v1, 0, r3, 0, new float[] { r2v1[0], r2v1[1], r2v1[2], 1 }, 0);

    if (!equalsAlmost(r3v3, u3, maxDiff)) {
        Matrix.setIdentityM(r3, 0);
        Matrix.rotateM(r3, 0, -angleDegrees, r2v2[0], r2v2[1], r2v2[2]);
        Matrix.multiplyMV(r3v3, 0, r3, 0, new float[] { r2v3[0], r2v3[1], r2v3[2], 1 }, 0);
        float[] r3v2 = new float[4];
        Matrix.multiplyMV(r3v2, 0, r3, 0, new float[] { r2v2[0], r2v2[1], r2v2[2], 1 }, 0);
        if (!equalsAlmost(r3v3, u3, maxDiff) || !equalsAlmost(r3v2, u2, maxDiff)) {
            return null;
        }
    }
    float[] subResult = new float[16];
    float[] subResult2 = new float[16];
    float[] subResult3 = new float[16];
    float[] totalResult = new float[16];
    float[] startMatrix = new float[16];
    Matrix.setIdentityM(startMatrix, 0);

    Matrix.multiplyMM(subResult, 0, toZeroTranslation, 0, startMatrix, 0);
    Matrix.multiplyMM(subResult2, 0, r2, 0, subResult, 0);
    Matrix.multiplyMM(subResult3, 0, r3, 0, subResult2, 0);
    Matrix.multiplyMM(totalResult, 0, translation, 0, subResult3, 0);

    return totalResult;
}

From source file:org.osm.keypadmapper2.KeypadMapper2Activity.java

/** 
 * THIS IS ONLY A TEST PROCEDURE mimicking Mapper.saveCurrentAddress() for
 * spotting duplicates./*from   w  ww  . ja v a  2s  .com*/
 * 
 * @param forward
 * @param left
 * @param locationToSave
 * @return
 */
public LocObj getCurrentAddress(double forward, double left, Location locationToSave) {
    LocObj locObj = new LocObj();

    forward /= 111111;
    left /= 111111;

    double lat = 0.0d;
    double lon = 0.0d;

    double speed = locationToSave.getSpeed();
    KeypadMapperSettings settings = KeypadMapperApplication.getInstance().getSettings();
    // convert meters per second to km/h or mph
    if (settings.getMeasurement().equals(KeypadMapperSettings.UNIT_METER)) {
        // meters
        speed = speed * KeypadMapperSettings.M_PER_SEC_HAS_KM_PER_HOUR;
    } else {
        // feet
        speed = speed * KeypadMapperSettings.M_PER_SEC_HAS_MILES_PER_HOUR;
    }

    if (settings.isCompassAvailable() && (((speed > 0.0 && settings.getUseCompassAtSpeed() > 0.0
            && speed < settings.getUseCompassAtSpeed())
            || (speed == 0.0 && settings.getUseCompassAtSpeed() > 0.0)))) {

        float azimuth = (float) Math.toDegrees(KeypadMapper2Activity.azimuth); // orientation
        if (azimuth < 0.0f) {
            azimuth = (azimuth + 360);
        }
        float bearing = azimuth;

        lat = (locationToSave.getLatitude() + Math.sin(Math.PI / 180 * bearing) * left
                + Math.cos(Math.PI / 180 * bearing) * forward);
        lon = (locationToSave.getLongitude()
                + (Math.sin(Math.PI / 180 * bearing) * forward - Math.cos(Math.PI / 180 * bearing) * left)
                        / Math.cos(Math.PI / 180 * locationToSave.getLatitude()));
        locObj.compassLat = lat;
        locObj.compassLon = lon;
    } else {
        // use bearing
        lat = (locationToSave.getLatitude() + Math.sin(Math.PI / 180 * locationToSave.getBearing()) * left
                + Math.cos(Math.PI / 180 * locationToSave.getBearing()) * forward);
        lon = (locationToSave.getLongitude() + (Math.sin(Math.PI / 180 * locationToSave.getBearing()) * forward
                - Math.cos(Math.PI / 180 * locationToSave.getBearing()) * left)
                / Math.cos(Math.PI / 180 * locationToSave.getLatitude()));
        locObj.gpsLat = lat;
        locObj.gpsLong = lon;
    }

    return locObj;
}

From source file:ffx.xray.DiffractionData.java

/**
 * write bulk solvent mask for dataset i to a CNS map file
 *
 * @param filename output filename//from w w w.ja v  a  2 s  .co  m
 * @param i dataset to write out
 */
public void writeSolventMaskCNS(String filename, int i) {
    if (solventModel != SolventModel.NONE) {
        try {
            PrintWriter cnsfile = new PrintWriter(new BufferedWriter(new FileWriter(filename)));
            cnsfile.println(" ANOMalous=FALSE");
            cnsfile.println(" DECLare NAME=FS DOMAin=RECIprocal TYPE=COMP END");
            for (HKL ih : reflectionList[i].hkllist) {
                int j = ih.index();
                cnsfile.printf(" INDE %d %d %d FS= %.4f %.4f\n", ih.h(), ih.k(), ih.l(),
                        refinementData[i].fsF(j), Math.toDegrees(refinementData[i].fsPhi(j)));
            }
            cnsfile.close();
        } catch (Exception e) {
            String message = "Fatal exception evaluating structure factors.\n";
            logger.log(Level.SEVERE, message, e);
            System.exit(-1);
        }
    }
}

From source file:uk.ac.diamond.scisoft.analysis.diffraction.PowderRingsUtils.java

/**
 * Create function which uses 6/7 parameters: wavelength (Angstrom), detector origin (mm), orientation angles (degrees)
 *//*  w  w w  .j  a  v a2 s.  c  om*/
static DetectorFitFunction createQFitFunction7(List<EllipticalROI> ellipses, DetectorProperties dp,
        double wavelength, boolean fixedWavelength) {
    int n = ellipses.size();
    double[][] known = new double[n][FitFunctionBase.nC];
    double[] weight = new double[n];

    double base = -calcBaseRollAngle(ellipses);
    logger.debug("Mean roll angle: {}", Math.toDegrees(base));

    for (int i = 0; i < n; i++) {
        EllipticalROI e = ellipses.get(i);
        weight[i] = e.getSemiAxis(0);
        int j = 0;
        double a = base - e.getAngle();
        for (double off : FitFunctionBase.angles) {
            double[] pt = e.getPoint(a + off);
            known[i][j++] = pt[0];
            known[i][j++] = pt[1];
        }
    }

    DetectorFitFunction f;
    Vector3d o = dp.getOrigin();
    double[] a = dp.getNormalAnglesInDegrees();
    if (fixedWavelength) {
        f = new QSpaceFitFixedWFunction7(known, weight, dp.getVPxSize(), wavelength);
        f.setInitial(o.getX(), o.getY(), o.getZ(), a[0], a[1], a[2]);
    } else {
        f = new QSpaceFitFunction7(known, weight, dp.getVPxSize());
        f.setInitial(wavelength, o.getX(), o.getY(), o.getZ(), a[0], a[1], a[2]);
    }
    f.setBaseRollAngle(base);
    return f;
}

From source file:com.appeaser.sublimepickerlibrary.timepicker.RadialTimePickerView.java

private int getDegreesFromXY(float x, float y, boolean constrainOutside) {
    // Ensure the point is inside the touchable area.
    final int innerBound;
    final int outerBound;
    if (mIs24HourMode && mShowHours) {
        innerBound = mMinDistForInnerNumber;
        outerBound = mMaxDistForOuterNumber;
    } else {/*from   ww w. j  a  va  2  s  .com*/
        final int index = mShowHours ? HOURS : MINUTES;
        final int center = mCircleRadius - mTextInset[index];
        innerBound = center - mSelectorRadius;
        outerBound = center + mSelectorRadius;
    }

    final double dX = x - mXCenter;
    final double dY = y - mYCenter;
    final double distFromCenter = Math.sqrt(dX * dX + dY * dY);
    if (distFromCenter < innerBound || constrainOutside && distFromCenter > outerBound) {
        return -1;
    }

    // Convert to degrees.
    final int degrees = (int) (Math.toDegrees(Math.atan2(dY, dX) + Math.PI / 2) + 0.5);
    if (degrees < 0) {
        return degrees + 360;
    } else {
        return degrees;
    }
}