Example usage for java.lang Math atan2

List of usage examples for java.lang Math atan2

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static double atan2(double y, double x) 

Source Link

Document

Returns the angle theta from the conversion of rectangular coordinates ( x ,  y ) to polar coordinates (r, theta).

Usage

From source file:com.l2jfree.gameserver.gameobjects.instance.L2AirShipInstance.java

/**
 * @param x// w w  w. j a v a2s .  c  o  m
 * @param y
 * @param z
 */
public void moveAirShipToLocation(int x, int y, int z, float speed) {
    final int curX = getX();
    final int curY = getY();

    // Calculate distance (dx,dy) between current position and destination
    final int dx = (x - curX);
    final int dy = (y - curY);
    double distance = Math.sqrt(dx * dx + dy * dy);

    if (_log.isDebugEnabled())
        _log.debug("distance to target:" + distance);

    // Define movement angles needed
    // ^
    // | X (x,y)
    // | /
    // | /distance
    // | /
    // |/ angle
    // X ---------->
    // (curx,cury)

    double cos;
    double sin;
    sin = dy / distance;
    cos = dx / distance;
    // Create and Init a MoveData object
    MoveData m = new MoveData();

    // Caclulate the Nb of ticks between the current position and the
    // destination
    int ticksToMove = (int) (GameTimeManager.TICKS_PER_SECOND * distance / speed);

    // Calculate and set the heading of the L2Creature
    int heading = (int) (Math.atan2(-sin, -cos) * 10430.378350470452724949566316381);
    heading += 32768;
    getPosition().setHeading(heading);

    if (_log.isDebugEnabled())
        _log.debug("dist:" + distance + "speed:" + speed + " ttt:" + ticksToMove + " heading:" + heading);

    m._xDestination = x;
    m._yDestination = y;
    m._zDestination = z; // this is what was requested from client
    m._heading = 0; // initial value for coordinate sync
    m.onGeodataPathIndex = -1; // Initialize not on geodata path
    m._moveStartTime = GameTimeManager.getGameTicks();

    if (_log.isDebugEnabled())
        _log.debug("time to target:" + ticksToMove);

    // Set the L2Creature _move object to MoveData object
    _move = m;

    // Add the L2Creature to movingObjects of the GameTimeController
    // The GameTimeController manage objects movement
    MovementController.getInstance().add(this, ticksToMove);
}

From source file:com.github.rosjava_catkin_package_a.ARLocROS.ARLoc.java

@Override
public void onStart(final ConnectedNode connectedNode) {
    // load OpenCV shared library
    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

    // read configuration variables from the ROS Runtime (configured in the
    // launch file)
    log = connectedNode.getLog();/*  www . ja  v  a2s .  c  om*/
    log.info("Reading parameters");
    this.parameter = Parameter.createFromParameterTree(connectedNode.getParameterTree());

    // Read Marker Config
    markerConfig = MarkerConfig.createFromConfig(parameter.markerConfigFile(), parameter.patternDirectory());

    // setup rotation vector and translation vector storing output of the
    // localization
    rvec = new Mat(3, 1, CvType.CV_64F);
    tvec = new MatOfDouble(1.0, 1.0, 1.0);

    camp = getCameraInfo(connectedNode, parameter);

    // start to listen to transform messages in /tf in order to feed the
    // Transformer and lookup transforms
    final TransformationService transformationService = TransformationService.create(connectedNode);

    // Subscribe to Image
    Subscriber<sensor_msgs.Image> subscriberToImage = connectedNode.newSubscriber(parameter.cameraImageTopic(),
            sensor_msgs.Image._TYPE);

    ComputePose computePose = null;
    try {
        final Mat cameraMatrix = CameraParams.getCameraMatrix(camp);
        final MatOfDouble distCoeffs = CameraParams.getDistCoeffs(camp);
        computePose = ComputePose.create(markerConfig, new Size(camp.width(), camp.height()), cameraMatrix,
                distCoeffs, this.parameter.visualization());
    } catch (NyARException e) {
        logger.info("Cannot initialize ComputePose", e);
    } catch (FileNotFoundException e) {
        logger.info("Cannot find file when initialize ComputePose", e);
    }
    final ComputePose poseProcessor = computePose;
    subscriberToImage.addMessageListener(new MessageListener<sensor_msgs.Image>() {

        @Override
        public void onNewMessage(sensor_msgs.Image message) {
            //
            if (!message.getEncoding().toLowerCase().equals("rgb8")) {
                log.error("Sorry, " + message.getEncoding() + " Image encoding is not supported! EXITING");
                System.exit(-1);
            }
            if (camp != null) {
                try {
                    //
                    image = Utils.matFromImage(message);
                    // uncomment to add more contrast to the image
                    //Utils.tresholdContrastBlackWhite(image, 600);
                    Imgproc.threshold(image, image, 200, 255, Imgproc.THRESH_BINARY);
                    // Mat cannyimg = new Mat(image.height(), image.width(),
                    // CvType.CV_8UC3);
                    // Imgproc.Canny(image, cannyimg, 10, 100);
                    // Imshow.show(cannyimg);

                    // image.convertTo(image, -1, 1.5, 0);
                    // setup camera matrix and return vectors
                    // compute pose
                    if (poseProcessor.computePose(rvec, tvec, image)) {
                        // notify publisher threads (pose and tf, see below)
                        synchronized (tvec) {
                            tvec.notifyAll();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    // publish tf CAMERA_FRAME_NAME --> MARKER_FRAME_NAME
    final Publisher<tf2_msgs.TFMessage> tfPublisherCamToMarker = connectedNode.newPublisher("tf",
            tf2_msgs.TFMessage._TYPE);
    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {

            synchronized (tvec) {
                tvec.wait();
            }

            QuaternionHelper q = new QuaternionHelper();

            /*
             * http://euclideanspace.com/maths/geometry/rotations/
             * conversions/matrixToEuler/index.htm
             * http://stackoverflow.com/questions/12933284/rodrigues-into-
             * eulerangles-and-vice-versa
             * 
             * heading = atan2(-m20,m00) attitude = asin(m10) bank =
             * atan2(-m12,m11)
             */
            // convert output rotation vector rvec to rotation matrix R
            Mat R = new Mat(3, 3, CvType.CV_32FC1);
            Calib3d.Rodrigues(rvec, R);
            // get rotations around X,Y,Z from rotation matrix R
            double bankX = Math.atan2(-R.get(1, 2)[0], R.get(1, 1)[0]);
            double headingY = Math.atan2(-R.get(2, 0)[0], R.get(0, 0)[0]);
            double attitudeZ = Math.asin(R.get(1, 0)[0]);
            // convert Euler angles to quarternion
            q.setFromEuler(bankX, headingY, attitudeZ);

            // set information to message
            TFMessage tfmessage = tfPublisherCamToMarker.newMessage();
            TransformStamped posestamped = connectedNode.getTopicMessageFactory()
                    .newFromType(geometry_msgs.TransformStamped._TYPE);
            Transform transform = posestamped.getTransform();

            Quaternion orientation = transform.getRotation();
            Vector3 point = transform.getTranslation();
            point.setX(tvec.get(0, 0)[0]);
            point.setY(tvec.get(1, 0)[0]);
            point.setZ(tvec.get(2, 0)[0]);

            orientation.setW(q.getW());
            orientation.setX(q.getX());
            orientation.setY(q.getY());
            orientation.setZ(q.getZ());
            posestamped.getHeader().setFrameId(parameter.cameraFrameName());
            posestamped.setChildFrameId(parameter.markerFrameName());
            posestamped.getHeader().setStamp(connectedNode.getCurrentTime());
            // frame_id too
            tfmessage.getTransforms().add(posestamped);
            tfPublisherCamToMarker.publish(tfmessage);
        }
    });

    // publish Markers
    final Publisher<visualization_msgs.Marker> markerPublisher = connectedNode.newPublisher("markers",
            visualization_msgs.Marker._TYPE);
    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {
            // publish markers every 500ms
            Thread.sleep(500);
            // get marker points from markerConfig, each marker has 4
            // vertices
            List<Point3> points3dlist = markerConfig.getUnordered3DPointList();
            int i = 0;
            for (Point3 p : points3dlist) {
                Marker markermessage = markerPublisher.newMessage();
                // FIXME If the markers are published into an existing frame
                // (e.g. map or odom) the node will consume very high CPU
                // and will fail after a short time. The markers are
                // probably published in the wrong way.
                markermessage.getHeader().setFrameId(parameter.markerFrameName());
                markermessage.setId(i);
                i++;
                markermessage.setType(visualization_msgs.Marker.SPHERE);
                markermessage.setAction(visualization_msgs.Marker.ADD);
                // position
                double x = p.x;
                markermessage.getPose().getPosition().setX(x);
                double y = p.y;
                markermessage.getPose().getPosition().setY(y);
                double z = p.z;
                markermessage.getPose().getPosition().setZ(z);
                // orientation
                markermessage.getPose().getOrientation().setX(0);
                markermessage.getPose().getOrientation().setY(0);
                markermessage.getPose().getOrientation().setZ(0);
                markermessage.getPose().getOrientation().setW(1);
                // patterntSize
                markermessage.getScale().setX(0.1);
                markermessage.getScale().setY(0.1);
                markermessage.getScale().setZ(0.1);
                // color
                markermessage.getColor().setA(1);
                markermessage.getColor().setR(1);
                markermessage.getColor().setG(0);
                markermessage.getColor().setB(0);

                markerPublisher.publish(markermessage);
            }
        }
    });

    // publish tf map --> odom
    final Publisher<tf2_msgs.TFMessage> tfPublisherMapToOdom = connectedNode.newPublisher("tf",
            tf2_msgs.TFMessage._TYPE);
    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {

            // since this is an infinite loop, wait to be notified if new
            // image was processed
            synchronized (tvec) {
                tvec.wait();
            }

            // compute transform map to odom from map to
            // camera_rgb_optical_frame and odom to camera_rgb_optical_frame

            // map to camera_rgb_optical_frame
            Mat tvec_map_cam = new MatOfDouble(1.0, 1.0, 1.0);
            QuaternionHelper q = new QuaternionHelper();
            // get rotation matrix R from solvepnp output rotation vector
            // rvec
            Mat R = new Mat(3, 3, CvType.CV_32FC1);
            Calib3d.Rodrigues(rvec, R);
            // transpose R, because we need the transformation from
            // world(map) to camera
            R = R.t();
            // get rotation around X,Y,Z from R in radiants
            double bankX = Math.atan2(-R.get(1, 2)[0], R.get(1, 1)[0]);
            double headingY = Math.atan2(-R.get(2, 0)[0], R.get(0, 0)[0]);
            double attitudeZ = Math.asin(R.get(1, 0)[0]);
            q.setFromEuler(bankX, headingY, attitudeZ);
            // compute translation vector from world (map) to cam
            // tvec_map_cam
            Core.multiply(R, new Scalar(-1), R); // R=-R
            Core.gemm(R, tvec, 1, new Mat(), 0, tvec_map_cam, 0); // tvec_map_cam=R*tvec

            org.ros.rosjava_geometry.Quaternion rotation = new org.ros.rosjava_geometry.Quaternion(q.getX(),
                    q.getY(), q.getZ(), q.getW());
            double x = tvec_map_cam.get(0, 0)[0];
            double y = tvec_map_cam.get(1, 0)[0];
            double z = tvec_map_cam.get(2, 0)[0];
            // create a Transform Object that hold the transform map to cam
            org.ros.rosjava_geometry.Vector3 translation = new org.ros.rosjava_geometry.Vector3(x, y, z);
            org.ros.rosjava_geometry.Transform transform_map_cam = new org.ros.rosjava_geometry.Transform(
                    translation, rotation);

            // odom to camera_rgb_optical_frame
            GraphName sourceFrame = GraphName.of(parameter.cameraFrameName());
            GraphName targetFrame = GraphName.of("odom");
            org.ros.rosjava_geometry.Transform transform_cam_odom = null;
            if (transformationService.canTransform(targetFrame, sourceFrame)) {
                try {
                    transform_cam_odom = transformationService.lookupTransform(targetFrame, sourceFrame);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to "
                            + "odom! " + "However, " + "will continue..");
                    return;
                }
            } else {
                log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to " + "odom! "
                        + "However, will " + "continue..");
                // cancel this loop..no result can be computed
                return;
            }
            // multiply results
            org.ros.rosjava_geometry.Transform result = org.ros.rosjava_geometry.Transform.identity();
            result = result.multiply(transform_map_cam);
            result = result.multiply(transform_cam_odom);

            // set information to ROS message
            TFMessage tfMessage = tfPublisherMapToOdom.newMessage();
            TransformStamped transformStamped = connectedNode.getTopicMessageFactory()
                    .newFromType(geometry_msgs.TransformStamped._TYPE);
            Transform transform = transformStamped.getTransform();

            Quaternion orientation = transform.getRotation();
            Vector3 vector = transform.getTranslation();
            vector.setX(result.getTranslation().getX());
            vector.setY(result.getTranslation().getY());
            vector.setZ(result.getTranslation().getZ());

            orientation.setW(result.getRotationAndScale().getW());
            orientation.setX(result.getRotationAndScale().getX());
            orientation.setY(result.getRotationAndScale().getY());
            orientation.setZ(result.getRotationAndScale().getZ());
            transformStamped.getHeader().setFrameId("map");
            transformStamped.setChildFrameId("odom");
            transformStamped.getHeader().setStamp(connectedNode.getCurrentTime());
            // frame_id too
            tfMessage.getTransforms().add(transformStamped);
            tfPublisherMapToOdom.publish(tfMessage);
            // System.exit(0);
        }
    });

    // Publish Pose

    final Publisher<geometry_msgs.PoseStamped> posePublisher = connectedNode
            .newPublisher(parameter.poseTopicName(), geometry_msgs.PoseStamped._TYPE);

    connectedNode.executeCancellableLoop(new CancellableLoop() {

        @Override
        protected void loop() throws InterruptedException {

            // since this is an infinite loop, wait here to be notified if
            // new image was processed
            synchronized (tvec) {
                tvec.wait();
            }
            final QuaternionHelper q = new QuaternionHelper();

            // convert rotation vector result of solvepnp to rotation matrix
            Mat R = new Mat(3, 3, CvType.CV_32FC1);
            Calib3d.Rodrigues(rvec, R);
            // see publishers before for documentation
            final Mat tvec_map_cam = new MatOfDouble(1.0, 1.0, 1.0);
            R = R.t();
            final double bankX = Math.atan2(-R.get(1, 2)[0], R.get(1, 1)[0]);
            final double headingY = Math.atan2(-R.get(2, 0)[0], R.get(0, 0)[0]);
            final double attitudeZ = Math.asin(R.get(1, 0)[0]);
            q.setFromEuler(bankX, headingY, attitudeZ);
            Core.multiply(R, new Scalar(-1), R);
            Core.gemm(R, tvec, 1, new Mat(), 0, tvec_map_cam, 0);
            final org.ros.rosjava_geometry.Quaternion rotation = new org.ros.rosjava_geometry.Quaternion(
                    q.getX(), q.getY(), q.getZ(), q.getW());
            final double x = tvec_map_cam.get(0, 0)[0];
            final double y = tvec_map_cam.get(1, 0)[0];
            final double z = tvec_map_cam.get(2, 0)[0];

            final org.ros.rosjava_geometry.Vector3 translation = new org.ros.rosjava_geometry.Vector3(x, y, z);
            final org.ros.rosjava_geometry.Transform transform_map_cam = new org.ros.rosjava_geometry.Transform(
                    translation, rotation);

            // odom to camera_rgb_optical_frame
            final GraphName sourceFrame = GraphName.of(parameter.cameraFrameName());
            final GraphName targetFrame = GraphName.of("base_link");
            org.ros.rosjava_geometry.Transform transform_cam_base = null;

            if (transformationService.canTransform(targetFrame, sourceFrame)) {
                try {
                    transform_cam_base = transformationService.lookupTransform(targetFrame, sourceFrame);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to "
                            + "base_link! " + "However, will continue..");
                    // cancel this loop..no result can be computed
                    return;
                }
            } else {
                log.info("Cloud not get transformation from " + parameter.cameraFrameName() + " to "
                        + "base_link!" + " However, " + "will continue..");
                // cancel this loop..no result can be computed
                return;
            }

            // multiply results
            org.ros.rosjava_geometry.Transform current_pose = org.ros.rosjava_geometry.Transform.identity();
            current_pose = current_pose.multiply(transform_map_cam);
            current_pose = current_pose.multiply(transform_cam_base);

            // check for plausibility of the pose by checking if movement
            // exceeds max speed (defined) of the robot
            if (parameter.badPoseReject()) {
                Time current_timestamp = connectedNode.getCurrentTime();
                // TODO Unfortunately, we do not have the tf timestamp at
                // hand here. So we can only use the current timestamp.
                double maxspeed = 5;
                boolean goodpose = false;
                // if (current_pose != null && current_timestamp != null) {
                if (last_pose != null && last_timestamp != null) {
                    // check speed of movement between last and current pose
                    double distance = PoseCompare.distance(current_pose, last_pose);
                    double timedelta = PoseCompare.timedelta(current_timestamp, last_timestamp);
                    if ((distance / timedelta) < maxspeed) {
                        if (smoothing) {
                            double xold = last_pose.getTranslation().getX();
                            double yold = last_pose.getTranslation().getY();
                            double zold = last_pose.getTranslation().getZ();
                            double xnew = current_pose.getTranslation().getX();
                            double ynew = current_pose.getTranslation().getY();
                            double znew = current_pose.getTranslation().getZ();
                            final org.ros.rosjava_geometry.Vector3 smoothTranslation = new org.ros.rosjava_geometry.Vector3(
                                    (xold * 2 + xnew) / 3, (yold * 2 + ynew) / 3, (zold * 2 + znew) / 3);
                            current_pose = new org.ros.rosjava_geometry.Transform(smoothTranslation,
                                    current_pose.getRotationAndScale());
                            last_pose = current_pose;
                        }
                        last_pose = current_pose;
                        last_timestamp = current_timestamp;
                        goodpose = true;
                    } else {
                        log.info("distance " + distance + " time: " + timedelta + " --> Pose rejected");
                    }

                } else {
                    last_pose = current_pose;
                    last_timestamp = current_timestamp;
                }
                // }
                // bad pose rejection
                if (!goodpose) {
                    return;
                }
            }

            // set information to message
            geometry_msgs.PoseStamped posestamped = posePublisher.newMessage();
            Pose pose = posestamped.getPose();
            Quaternion orientation = pose.getOrientation();
            Point point = pose.getPosition();

            point.setX(current_pose.getTranslation().getX());

            point.setY(current_pose.getTranslation().getY());

            point.setZ(current_pose.getTranslation().getZ());

            orientation.setW(current_pose.getRotationAndScale().getW());
            orientation.setX(current_pose.getRotationAndScale().getX());
            orientation.setY(current_pose.getRotationAndScale().getY());
            orientation.setZ(current_pose.getRotationAndScale().getZ());

            // frame_id too
            posestamped.getHeader().setFrameId("map");
            posestamped.getHeader().setStamp(connectedNode.getCurrentTime());
            posePublisher.publish(posestamped);

        }
    });

}

From source file:at.uni_salzburg.cs.ros.artificer.VehicleData.java

/**
 * {@inheritDoc}// www . j  a  v  a 2s .  c  o  m
 */
@Override
public void update() {
    if (startTime >= clock.currentTimeMillis()) {
        // do nothing, wait for new task.
        node.getLog().debug("Waiting for new task.");
        busy = false;

    } else if (endTime >= clock.currentTimeMillis()) {
        busy = true;
        currentTaskId = newTaskId;
        heading = newHeading;

        double completion = 1.0 - (endTime - clock.currentTimeMillis()) / (double) (endTime - startTime);
        CartesianCoordinate cp = distanceVector.multiply(completion * completion * (3 - 2 * completion))
                .add(cartesianStarPosition);
        PolarCoordinate pos = geodeticSystem.rectangularToPolarCoordinates(cp);
        currentPosition.setLatitude(pos.getLatitude());
        currentPosition.setLongitude(pos.getLongitude());
        currentPosition.setAltitude(pos.getAltitude());
        node.getLog().info(String.format("VehicleData.update() %f %d %d", completion,
                (endTime - clock.currentTimeMillis()), (endTime - startTime)));
    } else {
        newTaskId = incrementTaskCounter();
        currentTaskId = 0;

        node.getLog().info("Generate new task. " + newTaskId);
        startPosition = currentPosition;
        startTime = clock.currentTimeMillis()
                + (long) (MAXIMUM_WAIT_TIME_FOR_NEW_TASK * RandomUtils.nextDouble());
        busy = false;

        double latitude = minLat + (maxLat - minLat) * RandomUtils.nextDouble();
        double longitude = minLng + (maxLng - minLng) * RandomUtils.nextDouble();
        double altitude = minAlt + (maxAlt - minAlt) * RandomUtils.nextDouble();

        targetPosition.setLatitude(latitude);
        targetPosition.setLongitude(longitude);
        targetPosition.setAltitude(altitude);

        PolarCoordinate s = new PolarCoordinate(startPosition.getLatitude(), startPosition.getLongitude(),
                startPosition.getAltitude());

        PolarCoordinate t = new PolarCoordinate(targetPosition.getLatitude(), targetPosition.getLongitude(),
                targetPosition.getAltitude());

        cartesianStarPosition = geodeticSystem.polarToRectangularCoordinates(s);
        CartesianCoordinate target = geodeticSystem.polarToRectangularCoordinates(t);
        distanceVector = target.subtract(cartesianStarPosition);
        distance = distanceVector.norm();
        endTime = startTime + (long) (1000 * distance / velocity);

        if (Math.abs(t.getLatitude() - s.getLatitude()) < 1E-6
                && Math.abs(t.getLongitude() - s.getLongitude()) < 1E-6) {
            newHeading = 0;
        } else {
            newHeading = (float) Math.atan2(
                    (s.getLongitude() - t.getLongitude()) * Math.cos(t.getLatitude() * PI180TH),
                    t.getLatitude() - s.getLatitude());

            if (newHeading < 0) {
                newHeading += 2 * Math.PI;
            }

            newHeading /= PI180TH;
        }
    }
}

From source file:com.example.map.BasicMapActivity.java

private double hdistance(double lat, double lon, double lat2, double lon2) {
    final double EARTH_RADIUS = 6367.45; //km
    double deltaLat = lat2 - lat;
    double deltaLon = lon2 - lon;

    double a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2)
            + Math.cos(lat) * Math.cos(lat2) * Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return EARTH_RADIUS * c;
}

From source file:pw.dedominic.csc311_final_project.MainActivity.java

/**
 * Haversine formula to get distances of two points.
 * Points are given in Latitude and Longitude.
 *
 * @param lat1 latitude of point one//from w  w  w.j a  v a2 s  . com
 * @param lon1 longitude of point one
 * @param lat2 latitude of point two
 * @param lon2 longitude of point two
 */
private double getDistance(double lat1, double lat2, double lon1, double lon2) {
    double[] lat_rads = new double[2];
    lat_rads[0] = lat1 * Math.PI / 180;
    lat_rads[1] = lat2 * Math.PI / 180;

    double delta_lat = (lat2 - lat1) * Math.PI / 180;
    double delta_lon = (lon2 - lon1) * Math.PI / 180;

    double a = Math.pow(Math.sin(delta_lat / 2), 2)
            + Math.cos(lat_rads[0]) * Math.cos(lat_rads[1]) * Math.pow(Math.sin(delta_lon / 2), 2);

    double b = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return ((double) Constants.APPROX_RAD_EARTH) * b;
}

From source file:com.facebook.presto.operator.scalar.MathFunctions.java

@Description("arc tangent of given fraction")
@ScalarFunction//from www .  jav a2 s .co  m
@SqlType(StandardTypes.DOUBLE)
public static double atan2(@SqlType(StandardTypes.DOUBLE) double num1,
        @SqlType(StandardTypes.DOUBLE) double num2) {
    return Math.atan2(num1, num2);
}

From source file:pl.dp.bz.poid.fouriertest.FourierProc.java

public void computeEdgeDetectionFilter(int radiusExternal, int radiusInternal, int circleCenterX,
        int circleCenterY, double alpha1, double alpha2) {
    fourierImage = FourierProc.changeImageQuadrants(fourierImage);
    if (isCircleInImage(radiusExternal, circleCenterX, circleCenterY)
            && isCircleInImage(radiusInternal, circleCenterX, circleCenterY)) {
        for (int x = 0; x < imageWidth; x++) {
            for (int y = 0; y < imageHeight; y++) {
                if (x == imageWidth / 2 && y == imageHeight / 2) {
                    continue;
                }//from   www .j  a  v  a 2 s.  c o m
                if (computeDistance(circleCenterX, circleCenterY, x, y) > radiusExternal) {
                    fourierImage[x][y] = new Complex(0, 0);
                } else if (computeDistance(circleCenterX, circleCenterY, x, y) < radiusInternal) {
                    fourierImage[x][y] = new Complex(0, 0);
                } else {
                    //Tutaj wycinanie tych kawakw
                    //obliczamy x do ktrego trzeba
                    double px = x - imageWidth / 2;
                    double py = y - imageHeight / 2;
                    double d = Math.sqrt(px * px + py * py);
                    px /= d;
                    py /= d;
                    double aRad1 = Math.toRadians(alpha1);
                    double aRad2 = Math.toRadians(alpha2);
                    double a = Math.atan2(-py, -px) + Math.PI;
                    double a2 = Math.atan2(py, px) + Math.PI;
                    if ((aRad1 <= a && a <= aRad2) || (aRad1 <= a2 && a2 <= aRad2)) {
                        fourierImage[x][y] = new Complex(0, 0);
                    }
                }
            }
        }
    }
    fourierImage = FourierProc.changeImageQuadrants(fourierImage);
}

From source file:nl.b3p.viewer.stripes.OntbrandingsActionBean.java

private void calculateFan(JSONObject feature, JSONObject mainLocation, JSONArray gs)
        throws ParseException, TransformException {
    // Bereken centroide van feature: [1]
    // bereken centroide van hoofdlocatie: [2]
    // bereken lijn tussen de twee [1] en [2] centroides: [3]
    // bereken loodlijn op [3]: [4]
    // maak buffer in richting van [4] voor de fanafstand
    //Mogelijke verbetering, nu niet doen :// Voor elk vertex in feature, buffer met fan afstand in beiden richtingen van [4]
    // union alle buffers

    JSONObject attributes = feature.getJSONObject("attributes");
    double fanLength;
    double fanHeight;

    if (attributes.getString("fireworks_type").equals("consumer")) {
        fanLength = attributes.getDouble("zonedistance_consumer_m") * 1.5;
        fanHeight = attributes.getDouble("zonedistance_consumer_m");
    } else {//  ww w . j  a  v  a 2 s .c o m
        fanLength = attributes.getDouble("zonedistance_professional_m") * 1.5;
        fanHeight = attributes.getDouble("zonedistance_professional_m");
    }
    Geometry ignition = wkt.read(feature.getString("wktgeom"));
    Geometry audience = wkt.read(mainLocation.getString("wktgeom"));
    Geometry boundary = ignition.getBoundary();
    LineString boundaryLS = (LineString) boundary;
    LengthIndexedLine lil = new LengthIndexedLine(boundaryLS);

    Point ignitionCentroid = ignition.getCentroid();
    Point audienceCentroid = audience.getCentroid();

    double offset = fanHeight / 2;
    int endIndex = (int) lil.getEndIndex();

    Geometry zone = createNormalSafetyZone(feature, ignition);
    Geometry unioned = zone;

    double dx = ignitionCentroid.getX() - audienceCentroid.getX();
    double dy = ignitionCentroid.getY() - audienceCentroid.getY();

    // if (showIntermediateResults) {

    /* double length = ls.getLength();
    double ratioX = (dx / length);
    double ratioY = (dy / length);
    double fanX = ratioX * fanLength;
    double fanY = ratioY * fanLength;
    Point eindLoodlijn = gf.createPoint(new Coordinate(ignitionCentroid.getX() + fanX, ignitionCentroid.getY() + fanY));
    Coordinate ancorPoint = ignitionCentroid.getCoordinate();
            
    double angleRad = Math.toRadians(90);
    AffineTransform affineTransform = AffineTransform.getRotateInstance(angleRad, ancorPoint.x, ancorPoint.y);
    MathTransform mathTransform = new AffineTransform2D(affineTransform);
            
    Geometry rotatedPoint = JTS.transform(eindLoodlijn, mathTransform);
    Coordinate[] loodLijnCoords = {ignitionCentroid.getCoordinate(), rotatedPoint.getCoordinate()};
    LineString loodLijn = gf.createLineString(loodLijnCoords);*/
    /*  gs.put(createFeature(eindLoodlijn, "temp", "eindLoodlijn"));
    gs.put(createFeature(loodLijn, "temp", "loodLijn"));
    gs.put(createFeature(rotatedPoint, "temp", "loodLijn2"));*/
    //}

    double theta = Math.atan2(dy, dx);
    double correctBearing = (Math.PI / 2);
    double rotation = theta - correctBearing;
    for (int i = 0; i < endIndex; i += offset) {
        Coordinate c = lil.extractPoint(i);
        Geometry fan = createEllipse(c, rotation, fanLength, fanHeight, 220);

        if (!fan.isEmpty()) {
            unioned = unioned.union(fan);
        }
    }

    ConcaveHull con = new ConcaveHull(unioned, fanHeight);
    Geometry g = con.getConcaveHull();
    TopologyPreservingSimplifier tp = new TopologyPreservingSimplifier(g);
    tp.setDistanceTolerance(0.5);
    gs.put(createFeature(tp.getResultGeometry(), "safetyZone", ""));

    createSafetyDistances(gs, audience, ignition, g);
}

From source file:org.gearvrf.controls.util.VRSamplesTouchPadGesturesDetector.java

private SwipeDirection getSwipeDirection(float x1, float y1, float x2, float y2) {

    Double angle = Math.toDegrees(Math.atan2(y1 - y2, x2 - x1));

    if (angle > 45 && angle <= 135) {
        return SwipeDirection.Up;
    } else if (angle >= 135 && angle < 180 || angle < -135 && angle > -180) {
        return SwipeDirection.Ignore; // left to right
    } else if (angle < -45 && angle >= -135) {
        return SwipeDirection.Down;
    } else if (angle > -45 && angle <= 45) {
        return SwipeDirection.Ignore; // right to left
    }/* ww w .ja va 2s.  c om*/

    return SwipeDirection.Ignore;
}

From source file:ShapeTest.java

public Shape makeShape(Point2D[] p) {
    double centerX = (p[0].getX() + p[1].getX()) / 2;
    double centerY = (p[0].getY() + p[1].getY()) / 2;
    double width = Math.abs(p[1].getX() - p[0].getX());
    double height = Math.abs(p[1].getY() - p[0].getY());

    double skewedStartAngle = Math
            .toDegrees(Math.atan2(-(p[2].getY() - centerY) * width, (p[2].getX() - centerX) * height));
    double skewedEndAngle = Math
            .toDegrees(Math.atan2(-(p[3].getY() - centerY) * width, (p[3].getX() - centerX) * height));
    double skewedAngleDifference = skewedEndAngle - skewedStartAngle;
    if (skewedStartAngle < 0)
        skewedStartAngle += 360;/*w ww.  ja v a2 s.c  o m*/
    if (skewedAngleDifference < 0)
        skewedAngleDifference += 360;

    Arc2D s = new Arc2D.Double(0, 0, 0, 0, skewedStartAngle, skewedAngleDifference, Arc2D.OPEN);
    s.setFrameFromDiagonal(p[0], p[1]);

    GeneralPath g = new GeneralPath();
    g.append(s, false);
    Rectangle2D r = new Rectangle2D.Double();
    r.setFrameFromDiagonal(p[0], p[1]);
    g.append(r, false);
    Point2D center = new Point2D.Double(centerX, centerY);
    g.append(new Line2D.Double(center, p[2]), false);
    g.append(new Line2D.Double(center, p[3]), false);
    return g;
}