Beispiel #1
0
  /** Returns angle in degrees from specified origin to specified destination. */
  public static int getAngle(Point origin, Point destination) // origin != destination
      {
    double distance = getDistance(origin, destination);
    int add = 0;
    int x = destination.getx() - origin.getx();
    int y = origin.gety() - destination.gety(); // Java flips things around

    double angleRad = Math.asin(Math.abs(y) / distance);
    double angleDeg = Math.toDegrees(angleRad);

    if ((x >= 0) && (y >= 0)) // Quadrant 1
    {
      angleDeg = angleDeg;
    }
    if ((x < 0) && (y > 0)) // Quadrant 2
    {
      angleDeg = 180 - angleDeg;
    }
    if ((x <= 0) && (y <= 0)) // Quadrant 3
    {
      angleDeg = 180 + angleDeg;
    }
    if ((x > 0) && (y < 0)) // Quadrant 4
    {
      angleDeg = 360 - angleDeg;
    }

    float angleFloat = Math.round(angleDeg);
    int angleInt = Math.round(angleFloat);

    return (angleInt);
  }
Beispiel #2
0
  protected GameState.SystemSides findSystemSide(
      Point2D point, double rotationAngleInDegrees, double fieldWidth, double fieldHeight) {
    double centerX = point.getX(), centerY = point.getY();
    double angle = (rotationAngleInDegrees + 360) % 360;

    double angleLimits[] = new double[4];
    angleLimits[0] = Math.atan2(-centerY, fieldWidth - centerX);
    angleLimits[1] = Math.atan2(fieldHeight - centerY, fieldWidth - centerX);
    angleLimits[2] = Math.atan2(fieldHeight - centerY, -centerX);
    angleLimits[3] = Math.atan2(-centerY, -centerX);

    for (int i = 0; i < 4; i++) {
      angleLimits[i] = (Math.toDegrees(angleLimits[i]) + 360) % 360;
    }

    if (angle >= angleLimits[0] || angle <= angleLimits[1]) {
      return GameState.SystemSides.Right;
    } else if (angle < angleLimits[2]) {
      return GameState.SystemSides.Down;
    } else if (angle <= angleLimits[3]) {
      return GameState.SystemSides.Left;
    } else {
      return GameState.SystemSides.Up;
    }
  }
  public static double calAlpha(double theta, double dec) {
    if (Math.abs(dec) + theta > 89.9) return 180;

    return (double)
        Math.toDegrees(
            Math.abs(
                Math.atan(
                    Math.sin(Math.toRadians(theta))
                        / Math.sqrt(
                            Math.cos(Math.toRadians(dec - theta))
                                * Math.cos(Math.toRadians(dec + theta))))));
  }
Beispiel #4
0
 @Override
 public void onSensorChanged(SensorEvent event) {
   switch (event.sensor
       .getType()) { //  both accelerometer and magnetic data are needed to compute orientation
     case Sensor.TYPE_ACCELEROMETER:
       System.arraycopy(event.values, 0, accelValues, 0, 3);
       if (compassValues[0] != 0) sensorsReady = true;
       break;
     case Sensor.TYPE_MAGNETIC_FIELD:
       System.arraycopy(event.values, 0, compassValues, 0, 3);
       if (accelValues[2] != 0) sensorsReady = true;
       break;
     default:
       break;
   }
   if (sensorsReady
       && SensorManager.getRotationMatrix(inR, inclineMatrix, accelValues, compassValues)) {
     SensorManager.getOrientation(inR, prefValues);
     pitch = (float) Math.toDegrees(prefValues[1]);
     roll = (float) Math.toDegrees(prefValues[2]);
     if (mc != null) mc.updateOrientation(pitch, roll); // Update character's position
   }
 }
  /* CALCULATE VALUES QUADRANTS: Calculate x-y values where direction is not
  parallel to eith x or y axis. */
  public static void calcValuesQuad(int x1, int y1, int x2, int y2) {
    double arrowAng = Math.toDegrees(Math.atan((double) haw / (double) al));
    double dist = Math.sqrt(al * al + aw);
    double lineAng =
        Math.toDegrees(Math.atan(((double) Math.abs(x1 - x2)) / ((double) Math.abs(y1 - y2))));

    // Adjust line angle for quadrant
    if (x1 > x2) {
      // South East
      if (y1 > y2) lineAng = 180.0 - lineAng;
    } else {
      // South West
      if (y1 > y2) lineAng = 180.0 + lineAng;
      // North West
      else lineAng = 360.0 - lineAng;
    }

    // Calculate coords
    xValues[0] = x2;
    yValues[0] = y2;
    calcCoords(1, x2, y2, dist, lineAng - arrowAng);
    calcCoords(2, x2, y2, dist, lineAng + arrowAng);
  }
Beispiel #6
0
  private static LinkedList<Point2D> getCirclePoints(
      double centerLat, double centerLong, int numberOfPoints, double radius) {

    LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>();

    double lat1, long1;
    double d_rad;
    double delta_pts;
    double radial, lat_rad, dlon_rad, lon_rad;

    // convert coordinates to radians
    lat1 = Math.toRadians(centerLat);
    long1 = Math.toRadians(centerLong);

    // radius is in meters
    d_rad = radius / 6378137;

    // loop through the array and write points
    for (int i = 0; i <= numberOfPoints; i++) {
      delta_pts = 360 / (double) numberOfPoints;
      radial = Math.toRadians((double) i * delta_pts);

      // This algorithm is limited to distances such that dlon < pi/2
      lat_rad =
          Math.asin(
              Math.sin(lat1) * Math.cos(d_rad)
                  + Math.cos(lat1) * Math.sin(d_rad) * Math.cos(radial));
      dlon_rad =
          Math.atan2(
              Math.sin(radial) * Math.sin(d_rad) * Math.cos(lat1),
              Math.cos(d_rad) - Math.sin(lat1) * Math.sin(lat_rad));
      lon_rad = ((long1 + dlon_rad + Math.PI) % (2 * Math.PI)) - Math.PI;

      Point2Ds.add(new Point2D.Double(Math.toDegrees(lat_rad), Math.toDegrees(lon_rad)));
    }
    return Point2Ds;
  }
Beispiel #7
0
  public static void main(String[] args) {

    double zahl;
    scan = new Scanner(System.in);

    System.out.print("Bogenmass eingeben: ");
    zahl = scan.nextDouble();

    // Cosinus berechnen
    double ergebnis = Math.cos(zahl);

    // Ergebnis ausgeben
    System.out.println("Cosinus: " + ergebnis);
    System.out.println("In Grad: " + (Math.toDegrees(ergebnis)));
  }
Beispiel #8
0
    public void update() {
      Vector2D prevVector = main.getPosition().subtract(previous.getPosition());
      Vector2D nextVector = next.getPosition().subtract(main.getPosition());

      double angleRad =
          Math.acos(prevVector.dot(nextVector) / (prevVector.norm() * nextVector.norm()));
      double angle = Math.toDegrees(angleRad);
      if (prevVector.crossMag(nextVector) > 0) {
        angle = 360.0 - angle;
      }

      double forceMag = ANGLE_CONSTANT * (angle - 90.0);

      forces.put(previous, prevVector.rotate270().scaleTo(NEIGHBOR_ANGLE_SCALE * forceMag));
      forces.put(main, normals.get(main).scaleTo(forceMag));
      forces.put(next, nextVector.rotate270().scaleTo(NEIGHBOR_ANGLE_SCALE * forceMag));
    }
  public void run() {
    setAllColors(Color.GREEN);
    setTurnRadarRight(Double.POSITIVE_INFINITY);

    double robotX, robotY;
    double robotHeading, angleToGoal, angleToObs;
    double adjustment;
    double obsAngle, obsAdjustment;
    double angleDiff;
    double speedToGoal, speedFromObs;

    Enemy temp;
    obstacles = new HashMap<String, Enemy>(10);

    while (true) {
      if (foundGoal) {
        robotX = getX();
        robotY = getY();
        goalX = obstacles.get(GOAL_NAME).x;
        goalY = obstacles.get(GOAL_NAME).y;

        // Adjust robocode's returned heading so that 0 aligns with the positive x-axis instead of
        // the positive y-axis.
        // Also make it so that positive angle indicates a counter clockwise rotation instead of the
        // clockwise style
        // returned by robocode.
        robotHeading = 360 - (getHeading() - 90);
        angleToGoal = Math.toDegrees(Math.atan2(goalY - robotY, goalX - robotX));
        if (angleToGoal < 0) {
          angleToGoal += 360;
        }

        adjustment = angleToGoal - robotHeading;
        adjustment = normalizeAngle(adjustment);
        speedToGoal = calcRobotSpeedLinear(robotX, robotY, goalX, goalY);

        // Calculate how the robot's heading and speed should be affected by objects that it has
        // located
        // as it explores the world.
        Iterator it = obstacles.entrySet().iterator();
        while (it.hasNext()) {
          System.out.println("Iterating through objects.");

          Map.Entry pairs = (Map.Entry) it.next();

          // If the current item in the Iterator isn't the goal.
          if (!pairs.getKey().equals(GOAL_NAME)) {
            temp = (Enemy) pairs.getValue();
            speedFromObs = calcObjRepulseSpeed(robotX, robotY, temp.x, temp.y);

            // If the robot is in range of the object to be affected by it's repulsion.
            if (speedFromObs != 0) {
              obsAngle = Math.toDegrees(Math.atan2(robotY - temp.y, robotX - temp.x));
              if (obsAngle < 0) obsAngle += 360;

              angleDiff = obsAngle - angleToGoal;
              angleDiff = normalizeAngle(angleDiff);
              adjustment += (angleDiff * (speedFromObs / speedToGoal));
              speedToGoal -= speedFromObs;
            }
          }

          // Was getting a null pointer exception when using this. The internet lied about its
          // usefulness.
          // it.remove(); // avoids a ConcurrentModificationException
        }

        adjustment = normalizeAngle(adjustment);
        setTurnLeft(adjustment);
        // ahead(speedToGoal);
        setAhead(speedToGoal);
      }

      execute();
    }
  }
Beispiel #10
0
  public Move makeMove(double deltaTime) {
    Point2D tankPosition = getPlayerTank().getCenterPoint();
    switch (currentAction) {
      case Searching:
        if (target == null) {
          searchForTarget();
        }
        if (target != null) {
          currentAction = Action.ReachingTarget;
        }
        break;

      case ReachingTarget:
        if ((euclideanSpaceDistance(target, getPlayerTank().getCenterPoint()) < bonusRadius)) {
          target = null;
          isAngleSet = false;
        }
        if (target == null) {
          currentAction = Action.Searching;
          isSearchingStarted = false;
        }
        break;
    }

    switch (currentAction) {
      case Idle:
        break;

      case Searching:
        if (!isSearchingStarted) {
          rotationToDo = getBestRotationDirection();
          isSearchingStarted = true;
        }
        movementToDo = Move.Movement.Staying;
        break;

      case ReachingTarget:
        double bonusAngle =
            (Math.toDegrees(
                        Math.atan2(
                            target.getY() - tankPosition.getY(),
                            target.getX() - tankPosition.getX()))
                    + 360)
                % 360;
        double tankRotationAngle = (getPlayerTank().getRotationAngle() + 270) % 360;
        double bonusVisionAngle =
            (Math.toDegrees(Math.atan2(bonusRadius, euclideanSpaceDistance(tankPosition, target)))
                    + 360)
                % 360;
        double deltaAngle = (bonusAngle - tankRotationAngle + 360) % 360;

        double shift = euclideanSpaceDistance(tankPosition, lastPosition);
        double maxShift =
            2 * getPlayerTank().getVelocity() * (1.0 / GameState.getFramesPerSecond());
        if (shift > maxShift) {
          isAngleSet = false;
        }

        if (!isAngleSet) {
          if (deltaAngle < 180 + bonusVisionAngle && deltaAngle > 180 - bonusVisionAngle) {
            isAngleSet = true;
          } else if (deltaAngle >= 0 && deltaAngle <= 180 - bonusVisionAngle) {
            rotationToDo = Move.Rotation.CounterClockwise;
          } else if (deltaAngle >= 180 + bonusVisionAngle && deltaAngle < 360) {
            rotationToDo = Move.Rotation.Clockwise;
          }
          movementToDo = Move.Movement.Staying;
        } else {
          double tankRadius = getPlayerTank().getRadius();
          if (tankPosition.getY() - tankRadius <= tankRadius / 8) {
            if (tankRotationAngle >= 0 && tankRotationAngle < 90) {
              rotationToDo = Move.Rotation.CounterClockwise;
            } else if (tankRotationAngle > 90 && tankRotationAngle <= 180) {
              rotationToDo = Move.Rotation.Clockwise;
            }
          } else if (tankPosition.getX() + tankRadius
              >= GameState.getFieldWidth() - tankRadius / 8) {
            if (tankRotationAngle >= 90 && tankRotationAngle < 180) {
              rotationToDo = Move.Rotation.CounterClockwise;
            } else if (tankRotationAngle > 180 && tankRotationAngle <= 270) {
              rotationToDo = Move.Rotation.Clockwise;
            }
          } else if (tankPosition.getY() + tankRadius >= GameState.fieldHeight - tankRadius / 8) {
            if (tankRotationAngle >= 180 && tankRotationAngle < 270) {
              rotationToDo = Move.Rotation.CounterClockwise;
            } else if (tankRotationAngle > 270 && tankRotationAngle <= 360) {
              rotationToDo = Move.Rotation.Clockwise;
            }
          } else if (tankPosition.getX() - tankRadius <= tankRadius / 8) {
            if (tankRotationAngle >= 270 && tankRotationAngle < 360) {
              rotationToDo = Move.Rotation.CounterClockwise;
            } else if (tankRotationAngle > 0 && tankRotationAngle <= 90) {
              rotationToDo = Move.Rotation.Clockwise;
            }
          } else {
            rotationToDo = Move.Rotation.Staying;
          }
          if (rotationToDo != Move.Rotation.Staying) {
            isAngleSet = false;
          }
          movementToDo = Move.Movement.Backward;
        }

        lastPosition = getPlayerTank().getCenterPoint();

        break;
    }

    return new Move(movementToDo, rotationToDo, shootingToDo);
  }
 // To add/remove functions change evaluateOperator() and registration
 public double evaluateFunction(String fncnam, ArgParser fncargs) throws ArithmeticException {
   switch (Character.toLowerCase(fncnam.charAt(0))) {
     case 'a':
       {
         if (fncnam.equalsIgnoreCase("abs")) {
           return Math.abs(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("acos")) {
           return Math.acos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("asin")) {
           return Math.asin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("atan")) {
           return Math.atan(fncargs.next());
         }
       }
       break;
     case 'c':
       {
         if (fncnam.equalsIgnoreCase("cbrt")) {
           return Math.cbrt(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("ceil")) {
           return Math.ceil(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cos")) {
           return Math.cos(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("cosh")) {
           return Math.cosh(fncargs.next());
         }
       }
       break;
     case 'e':
       {
         if (fncnam.equalsIgnoreCase("exp")) {
           return Math.exp(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("expm1")) {
           return Math.expm1(fncargs.next());
         }
       }
       break;
     case 'f':
       {
         if (fncnam.equalsIgnoreCase("floor")) {
           return Math.floor(fncargs.next());
         }
       }
       break;
     case 'g':
       {
         //              if(fncnam.equalsIgnoreCase("getExponent"   )) { return
         // Math.getExponent(fncargs.next());                } needs Java 6
       }
       break;
     case 'l':
       {
         if (fncnam.equalsIgnoreCase("log")) {
           return Math.log(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log10")) {
           return Math.log10(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("log1p")) {
           return Math.log1p(fncargs.next());
         }
       }
       break;
     case 'm':
       {
         if (fncnam.equalsIgnoreCase("max")) {
           return Math.max(fncargs.next(), fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("min")) {
           return Math.min(fncargs.next(), fncargs.next());
         }
       }
       break;
     case 'n':
       {
         //              if(fncnam.equalsIgnoreCase("nextUp"        )) { return Math.nextUp
         // (fncargs.next());                } needs Java 6
       }
       break;
     case 'r':
       {
         if (fncnam.equalsIgnoreCase("random")) {
           return Math.random();
         } // impure
         if (fncnam.equalsIgnoreCase("round")) {
           return Math.round(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("roundHE")) {
           return Math.rint(fncargs.next());
         } // round half-even
       }
       break;
     case 's':
       {
         if (fncnam.equalsIgnoreCase("signum")) {
           return Math.signum(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sin")) {
           return Math.sin(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sinh")) {
           return Math.sinh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("sqrt")) {
           return Math.sqrt(fncargs.next());
         }
       }
       break;
     case 't':
       {
         if (fncnam.equalsIgnoreCase("tan")) {
           return Math.tan(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("tanh")) {
           return Math.tanh(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toDegrees")) {
           return Math.toDegrees(fncargs.next());
         }
         if (fncnam.equalsIgnoreCase("toRadians")) {
           return Math.toRadians(fncargs.next());
         }
       }
       break;
     case 'u':
       {
         if (fncnam.equalsIgnoreCase("ulp")) {
           return Math.ulp(fncargs.next());
         }
       }
       break;
       // no default
   }
   throw new UnsupportedOperationException(
       "MathEval internal function setup is incorrect - internal function \""
           + fncnam
           + "\" not handled");
 }
  public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask)
      throws IOException {
    NexradStationDB.init();

    volScan = new Cinrad2VolumeScan(raf, cancelTask);
    if (volScan.hasDifferentDopplarResolutions())
      throw new IllegalStateException("volScan.hasDifferentDopplarResolutions");

    radialDim = new Dimension("radial", volScan.getMaxRadials());
    ncfile.addDimension(null, radialDim);

    makeVariable(
        ncfile,
        Cinrad2Record.REFLECTIVITY,
        "Reflectivity",
        "Reflectivity",
        "R",
        volScan.getReflectivityGroups());
    int velocity_type =
        (volScan.getDopplarResolution() == Cinrad2Record.DOPPLER_RESOLUTION_HIGH_CODE)
            ? Cinrad2Record.VELOCITY_HI
            : Cinrad2Record.VELOCITY_LOW;
    Variable v =
        makeVariable(
            ncfile,
            velocity_type,
            "RadialVelocity",
            "Radial Velocity",
            "V",
            volScan.getVelocityGroups());
    makeVariableNoCoords(
        ncfile, Cinrad2Record.SPECTRUM_WIDTH, "SpectrumWidth", "Spectrum Width", v);

    if (volScan.getStationId() != null) {
      ncfile.addAttribute(null, new Attribute("Station", volScan.getStationId()));
      ncfile.addAttribute(null, new Attribute("StationName", volScan.getStationName()));
      ncfile.addAttribute(
          null, new Attribute("StationLatitude", new Double(volScan.getStationLatitude())));
      ncfile.addAttribute(
          null, new Attribute("StationLongitude", new Double(volScan.getStationLongitude())));
      ncfile.addAttribute(
          null,
          new Attribute("StationElevationInMeters", new Double(volScan.getStationElevation())));

      double latRadiusDegrees = Math.toDegrees(radarRadius / ucar.unidata.geoloc.Earth.getRadius());
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lat_min", new Double(volScan.getStationLatitude() - latRadiusDegrees)));
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lat_max", new Double(volScan.getStationLatitude() + latRadiusDegrees)));
      double cosLat = Math.cos(Math.toRadians(volScan.getStationLatitude()));
      double lonRadiusDegrees =
          Math.toDegrees(radarRadius / cosLat / ucar.unidata.geoloc.Earth.getRadius());
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lon_min", new Double(volScan.getStationLongitude() - lonRadiusDegrees)));
      ncfile.addAttribute(
          null,
          new Attribute(
              "geospatial_lon_max", new Double(volScan.getStationLongitude() + lonRadiusDegrees)));

      // add a radial coordinate transform (experimental)
      Variable ct = new Variable(ncfile, null, null, "radialCoordinateTransform");
      ct.setDataType(DataType.CHAR);
      ct.setDimensions(""); // scalar
      ct.addAttribute(new Attribute("transform_name", "Radial"));
      ct.addAttribute(new Attribute("center_latitude", new Double(volScan.getStationLatitude())));
      ct.addAttribute(new Attribute("center_longitude", new Double(volScan.getStationLongitude())));
      ct.addAttribute(new Attribute("center_elevation", new Double(volScan.getStationElevation())));
      ct.addAttribute(new Attribute(_Coordinate.TransformType, "Radial"));
      ct.addAttribute(
          new Attribute(_Coordinate.AxisTypes, "RadialElevation RadialAzimuth RadialDistance"));

      Array data =
          Array.factory(DataType.CHAR.getPrimitiveClassType(), new int[0], new char[] {' '});
      ct.setCachedData(data, true);
      ncfile.addVariable(null, ct);
    }

    DateFormatter formatter = new DateFormatter();

    ncfile.addAttribute(null, new Attribute(CDM.CONVENTIONS, _Coordinate.Convention));
    ncfile.addAttribute(null, new Attribute("format", volScan.getDataFormat()));
    ncfile.addAttribute(null, new Attribute(CF.FEATURE_TYPE, FeatureType.RADIAL.toString()));
    // Date d = Cinrad2Record.getDate(volScan.getTitleJulianDays(), volScan.getTitleMsecs());
    // ncfile.addAttribute(null, new Attribute("base_date", formatter.toDateOnlyString(d)));

    ncfile.addAttribute(
        null,
        new Attribute(
            "time_coverage_start", formatter.toDateTimeStringISO(volScan.getStartDate())));
    ; // .toDateTimeStringISO(d)));
    ncfile.addAttribute(
        null,
        new Attribute("time_coverage_end", formatter.toDateTimeStringISO(volScan.getEndDate())));

    ncfile.addAttribute(
        null,
        new Attribute(CDM.HISTORY, "Direct read of Nexrad Level 2 file into NetCDF-Java 2.2 API"));
    ncfile.addAttribute(null, new Attribute("DataType", "Radial"));

    ncfile.addAttribute(
        null,
        new Attribute(
            "Title",
            "Nexrad Level 2 Station "
                + volScan.getStationId()
                + " from "
                + formatter.toDateTimeStringISO(volScan.getStartDate())
                + " to "
                + formatter.toDateTimeStringISO(volScan.getEndDate())));

    ncfile.addAttribute(
        null,
        new Attribute(
            "Summary",
            "Weather Surveillance Radar-1988 Doppler (WSR-88D) "
                + "Level II data are the three meteorological base data quantities: reflectivity, mean radial velocity, and "
                + "spectrum width."));

    ncfile.addAttribute(
        null,
        new Attribute(
            "keywords",
            "WSR-88D; NEXRAD; Radar Level II; reflectivity; mean radial velocity; spectrum width"));

    ncfile.addAttribute(
        null,
        new Attribute(
            "VolumeCoveragePatternName",
            Cinrad2Record.getVolumeCoveragePatternName(volScan.getVCP())));
    ncfile.addAttribute(
        null, new Attribute("VolumeCoveragePattern", new Integer(volScan.getVCP())));
    ncfile.addAttribute(
        null,
        new Attribute(
            "HorizonatalBeamWidthInDegrees", new Double(Cinrad2Record.HORIZONTAL_BEAM_WIDTH)));

    ncfile.finish();
  }