Example #1
0
    void draw(Graphics2D g) {

      // toX/toY is tip of arrow and fx/fy is a point on the line -
      // fx/fy is used to determine direction & angle

      AffineTransform at = AffineTransform.getTranslateInstance(toX, toY);
      int b = 9;
      double theta = Math.toRadians(20);
      // The idea of using a GeneralPath is so we can
      // create the (three lines that make up the) arrow
      // (only) one time and then use AffineTransform to
      // place it anywhere we want.
      GeneralPath path = new GeneralPath();

      // distance between line and the arrow mark <** not **
      // Start a new line segment from the position of (0,0).
      path.moveTo(0, 0);
      // Create one of the two arrow head lines.
      int x = (int) (-b * Math.cos(theta));
      int y = (int) (b * Math.sin(theta));
      path.lineTo(x, y);

      // distance between line and the arrow mark <** not **
      // Make the other arrow head line.
      int x2 = (int) (-b * Math.cos(-theta));
      int y2 = (int) (b * Math.sin(-theta));
      // path.moveTo(0,0);
      path.lineTo(x2, y2);
      path.closePath();

      // theta is in radians
      double s, t;
      s = toY - fy; // calculate slopes.
      t = toX - fx;
      if (t != 0) {
        s = s / t;
        theta = Math.atan(s);
        if (t < 0) theta += Math.PI;
      } else if (s < 0) theta = -(Math.PI / 2);
      else theta = Math.PI / 2;

      at.rotate(theta);
      // at.rotate(theta,toX,toY);
      Shape shape = at.createTransformedShape(path);
      if (checkStatus == Status.UNCHECKED) g.setColor(Color.BLACK);
      else if (checkStatus == Status.COMPATIBLE) g.setColor(FOREST_GREEN);
      else g.setColor(ORANGE_RED);
      g.fill(shape);
      g.draw(shape);
    }
Example #2
0
 void draw(Graphics2D g) {
   g.setColor(darkColor);
   int x = (int) (center_x + distance * Math.sin(-unit * current / num));
   int y = (int) (center_y + distance * Math.cos(-unit * current / num));
   Area area = new Area(new Ellipse2D.Double(x, y, ball_r, ball_r));
   g.fill(area);
 }
Example #3
0
 public void calc() {
   try {
     // 取得輸入區的字串, 轉成浮點數後除以角度換算單位
     double theta = Double.parseDouble(degree.getText()) / convert;
     // 計算三角函數值, 並將結果寫到各文字欄位中
     sintxt.setText(String.format("%.3f", Math.sin(theta)));
     costxt.setText(String.format("%.3f", Math.cos(theta)));
     tantxt.setText(String.format("%.3f", Math.tan(theta)));
   } catch (NumberFormatException e) {
     degree.setText(""); // 發生例外時清除輸入區內容
   }
 }
 public void loseCoins() {
   int x = player1.getX();
   int y = player1.getY();
   double losePercentage = 0.1;
   for (int i = 0;
       i < (int) coins * losePercentage;
       i++) { // makes the user lose 10 percent of the coin and draws them in a circle
     // System.out.println(i);
     int xPos = x + (int) (100 * Math.cos(Math.toRadians((360 / (coins * losePercentage)) * i)));
     int yPos = y - (int) (100 * Math.sin(Math.toRadians((360 / (coins * losePercentage)) * i)));
     coinList.add(new Coin(xPos, yPos, 3));
   }
   coins -= (int) (coins * losePercentage);
 }
    @Override
    protected void paintComponent(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;

      final Dimension size = getSize();
      int _size = Math.min(size.width, size.height);
      _size = Math.min(_size, 600);

      if (myImage != null && myShouldInvalidate) {
        if (myImage.getWidth(null) != _size) {
          myImage = null;
        }
      }

      myShouldInvalidate = false;

      if (myImage == null) {
        myImage =
            createImage(
                new ColorWheelImageProducer(
                    _size - BORDER_SIZE * 2, _size - BORDER_SIZE * 2, myBrightness));
        myWheel =
            new Rectangle(
                BORDER_SIZE, BORDER_SIZE, _size - BORDER_SIZE * 2, _size - BORDER_SIZE * 2);
      }

      g.setColor(UIManager.getColor("Panel.background"));
      g.fillRect(0, 0, getWidth(), getHeight());

      g2d.setComposite(
          AlphaComposite.getInstance(AlphaComposite.SRC_OVER, ((float) myOpacity) / 255f));
      g.drawImage(myImage, myWheel.x, myWheel.y, null);

      g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));

      int mx = myWheel.x + myWheel.width / 2;
      int my = myWheel.y + myWheel.height / 2;
      //noinspection UseJBColor
      g.setColor(Color.WHITE);
      int arcw = (int) (myWheel.width * mySaturation / 2);
      int arch = (int) (myWheel.height * mySaturation / 2);
      double th = myHue * 2 * Math.PI;
      final int x = (int) (mx + arcw * Math.cos(th));
      final int y = (int) (my - arch * Math.sin(th));
      g.fillRect(x - 2, y - 2, 4, 4);
      //noinspection UseJBColor
      g.setColor(Color.BLACK);
      g.drawRect(x - 2, y - 2, 4, 4);
    }
Example #6
0
  /** Recalculates the (x,y) point used to indicate the selected color. */
  private void regeneratePoint() {
    int size =
        Math.min(
            MAX_SIZE,
            Math.min(
                getWidth() - imagePadding.left - imagePadding.right,
                getHeight() - imagePadding.top - imagePadding.bottom));
    if (mode == ColorPicker.HUE || mode == ColorPicker.SAT || mode == ColorPicker.BRI) {
      if (mode == ColorPicker.HUE) {
        point = new Point((int) (sat * size), (int) (bri * size));
      } else if (mode == ColorPicker.SAT) {
        double theta = hue * 2 * Math.PI - Math.PI / 2;
        if (theta < 0) theta += 2 * Math.PI;

        double r = bri * size / 2;
        point =
            new Point(
                (int) (r * Math.cos(theta) + .5 + size / 2.0),
                (int) (r * Math.sin(theta) + .5 + size / 2.0));
      } else if (mode == ColorPicker.BRI) {
        double theta = hue * 2 * Math.PI - Math.PI / 2;
        if (theta < 0) theta += 2 * Math.PI;
        double r = sat * size / 2;
        point =
            new Point(
                (int) (r * Math.cos(theta) + .5 + size / 2.0),
                (int) (r * Math.sin(theta) + .5 + size / 2.0));
      }
    } else if (mode == ColorPicker.RED) {
      point = new Point((int) (green * size / 255f + .49f), (int) (blue * size / 255f + .49f));
    } else if (mode == ColorPicker.GREEN) {
      point = new Point((int) (red * size / 255f + .49f), (int) (blue * size / 255f + .49f));
    } else if (mode == ColorPicker.BLUE) {
      point = new Point((int) (red * size / 255f + .49f), (int) (green * size / 255f + .49f));
    }
  }
  public void flecha(Graphics papel, int x1, int y1, int x2, int y2) {
    double ang = 0.0, angSep = 0.0;
    double tx = 0, ty = 0;
    int dist = 0;
    Point punto1 = null, punto2 = null;

    punto2 = new Point(x1, y1);
    punto1 = new Point(x2, y2);

    dist = 15;

    ty = -(punto1.y - punto2.y) * 1.0;
    tx = (punto1.x - punto2.x) * 1.0;
    ang = Math.atan(ty / tx);

    if (tx < 0) ang += Math.PI;
    Point p1 = new Point(), p2 = new Point(), punto = punto2;
    angSep = 25.0;

    p1.x = (int) (punto.x + dist * Math.cos(ang - Math.toRadians(angSep)));
    p1.y = (int) (punto.y - dist * Math.sin(ang - Math.toRadians(angSep)));
    p2.x = (int) (punto.x + dist * Math.cos(ang + Math.toRadians(angSep)));
    p2.y = (int) (punto.y - dist * Math.sin(ang + Math.toRadians(angSep)));

    Graphics2D g2D = (Graphics2D) papel;
    papel.setColor(Color.black);
    g2D.setStroke(new BasicStroke(1.2f));
    papel.drawLine(punto1.x, punto1.y, punto.x, punto.y);

    int x[] = {p1.x, punto.x, p2.x};
    int y[] = {p1.y, punto.y, p2.y};
    Polygon myTri = new Polygon(x, y, 3);
    papel.setColor(Color.BLACK);
    papel.drawPolygon(myTri);
    papel.fillPolygon(myTri);
  }
Example #8
0
  protected void recalcOutFreq() {
    if (inRate == 0f) return;

    double omegaIn, omegaOut, warp;
    ParamField ggOutFreq;

    omegaIn = pr.para[PR_INFREQ].val / inRate * Constants.PI2;
    warp = Math.max(-0.98, Math.min(0.98, pr.para[PR_WARP].val / 100)); // DAFx2000 'b'
    omegaOut = omegaIn + 2 * Math.atan2(warp * Math.sin(omegaIn), 1.0 - warp * Math.cos(omegaIn));

    ggOutFreq = (ParamField) gui.getItemObj(GG_OUTFREQ);
    if (ggOutFreq != null) {
      ggOutFreq.setParam(new Param(omegaOut / Constants.PI2 * inRate, Param.ABS_HZ));
    }
  }
Example #9
0
 private Path2D.Double makeStar(int r1, int r2, int vc) {
   int or = Math.max(r1, r2);
   int ir = Math.min(r1, r2);
   double agl = 0d;
   double add = 2 * Math.PI / (vc * 2);
   Path2D.Double p = new Path2D.Double();
   p.moveTo(or * 1, or * 0);
   for (int i = 0; i < vc * 2 - 1; i++) {
     agl += add;
     int r = i % 2 == 0 ? ir : or;
     p.lineTo(r * Math.cos(agl), r * Math.sin(agl));
   }
   p.closePath();
   AffineTransform at = AffineTransform.getRotateInstance(-Math.PI / 2, or, 0);
   return new Path2D.Double(p, at);
 }
Example #10
0
  public void recalcCrossLine() {
    Vector2d dir =
        new Vector2d(
            Math.cos(Math.PI * crossLineAngleDegree / 180.0),
            Math.sin(Math.PI * crossLineAngleDegree / 180.0));
    crossLine.p0.set(modelCenter.x - dir.x * 300, modelCenter.y - dir.y * 300);
    crossLine.p1.set(modelCenter.x + dir.x * 300, modelCenter.y + dir.y * 300);
    Vector2d moveVec = new Vector2d(-dir.y, dir.x);
    moveVec.normalize();
    moveVec.scale(crossLinePosition);
    crossLine.p0.add(moveVec);
    crossLine.p1.add(moveVec);

    ORIPA.doc.setCrossLine(crossLine);
    repaint();
    ORIPA.mainFrame.mainScreen.repaint();
  }
Example #11
0
  protected void recalcWarpAmount() {
    if (inRate == 0f) return;

    double omegaIn, omegaOut, warp, d1;
    ParamField ggWarp;

    omegaIn = pr.para[PR_INFREQ].val / inRate * Constants.PI2;
    omegaOut = pr.para[PR_OUTFREQ].val / inRate * Constants.PI2;
    d1 = Math.tan((omegaOut - omegaIn) / 2);
    warp =
        Math.max(
            -0.98,
            Math.min(0.98, d1 / (Math.sin(omegaIn) + Math.cos(omegaIn) * d1))); // DAFx2000 'b'

    ggWarp = (ParamField) gui.getItemObj(GG_WARP);
    if (ggWarp != null) {
      ggWarp.setParam(new Param(warp * 100, Param.FACTOR));
    }
  }
Example #12
0
  /*
   *  Defines a simple transformation matrix
   *  Outputs the transformation matrix
   */
  public static double[][] DefineElementaryTransform(
      double[][] inputMatrix, TRANSFORM_CODE transformCode, double transformValue) {
    double[][] transMatrix = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}};
    double[][] retMatrix = new double[4][4];
    double radianVal = Math.PI * transformValue / 180;

    switch (transformCode) {
      case X_TRANS:
        transMatrix[3][0] = transformValue;
        break;
      case Y_TRANS:
        transMatrix[3][1] = transformValue;
        break;
      case Z_TRANS:
        transMatrix[3][2] = transformValue;
        break;
      case Y_ROT:
        transMatrix[0][0] = Math.cos(radianVal);
        transMatrix[0][2] = -Math.sin(radianVal);
        transMatrix[2][0] = Math.sin(radianVal);
        transMatrix[2][2] = Math.cos(radianVal);
        break;
      case X_ROT:
        transMatrix[1][1] = Math.cos(radianVal);
        transMatrix[1][2] = Math.sin(radianVal);
        transMatrix[2][1] = -Math.sin(radianVal);
        transMatrix[2][2] = Math.cos(radianVal);
        break;
      case Z_ROT:
        transMatrix[0][0] = Math.cos(radianVal);
        transMatrix[0][1] = Math.sin(radianVal);
        transMatrix[1][0] = -Math.sin(radianVal);
        transMatrix[1][1] = Math.cos(radianVal);
        break;
      case PERSPECTIVE:
        assert (transformValue != 0);
        transMatrix[2][3] = -1 / transformValue;
        break;
      default:
        System.out.println("Error: invalid code passed into function DefineElementaryTransform");
        break;
    }

    retMatrix = MultiplyTransforms(inputMatrix, transMatrix);
    return retMatrix;
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();

    Molecule molecule = new Molecule("H");
    SiteType[] type = new SiteType[Colors.COLORARRAY.length];
    for (int i = 0; i < type.length; i++) {
      type[i] = new SiteType(molecule, "Type " + i);
      type[i].setRadius(1 + 0.5 * (i % 3));
      type[i].setColor(Colors.COLORARRAY[i]);
      molecule.addType(type[i]);
    }
    Site[] site = new Site[3 * type.length];
    for (int i = 0; i < site.length; i++) {
      site[i] = new Site(molecule, type[i % type.length]);
      site[i].setX(30 * Math.cos(2 * Math.PI * i / site.length));
      site[i].setY(30 * Math.sin(2 * Math.PI * i / site.length));
      site[i].setZ(6);
      site[i].setLocation(SystemGeometry.INSIDE);
      molecule.addSite(site[i]);
    }
    Link[] link = new Link[site.length - 1];
    for (int i = 0; i < link.length; i++) {
      link[i] = new Link(site[i], site[i + 1]);
      molecule.addLink(link[i]);
    }

    DrawPanel3D panel3d = new DrawPanel3D(molecule);

    DrawPanel3DPanel panel = new DrawPanel3DPanel(panel3d);

    Container c = frame.getContentPane();
    c.add(panel);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setSize(600, 400);
    frame.setVisible(true);
  }
Example #14
0
  private void spawnCircles() {
    if (circular) {
      for (int i = 0; i < ballN; i++) {
        double degree = Math.random() * 2 * Math.PI;
        float x = ((Player) players.get(0)).getX() + distance * (float) Math.sin(degree * i);
        float y = ((Player) players.get(0)).getY() + distance * (float) Math.cos(degree * i);
        enemies.add(new EnemyTypes.Circle(x, y, invSpeed));
      }
    } else {
      for (int i = 1; i < (ballN / 2); i++) {
        float x = (i * 2 * width) / (ballN);
        float y = 0;
        enemies.add(new EnemyTypes.Circle(x, y, invSpeed));
      }

      for (int i = (ballN / 2) + 1; i < ballN; i++) {
        float x = ((i - ballN / 2) * 2 * width) / ballN;
        float y = height;
        enemies.add(new EnemyTypes.Circle(x, y, invSpeed));
      }
    }
    spawnIncrease = false;
  }
Example #15
0
  /** Rotate theta degrees about the x axis */
  void xrot(double theta) {
    theta *= (pi / 180);
    double ct = Math.cos(theta);
    double st = Math.sin(theta);

    double Nyx = (yx * ct + zx * st);
    double Nyy = (yy * ct + zy * st);
    double Nyz = (yz * ct + zz * st);
    double Nyo = (yo * ct + zo * st);

    double Nzx = (zx * ct - yx * st);
    double Nzy = (zy * ct - yy * st);
    double Nzz = (zz * ct - yz * st);
    double Nzo = (zo * ct - yo * st);

    yo = Nyo;
    yx = Nyx;
    yy = Nyy;
    yz = Nyz;
    zo = Nzo;
    zx = Nzx;
    zy = Nzy;
    zz = Nzz;
  }
Example #16
0
  /** Rotate theta degrees about the z axis */
  void zrot(double theta) {
    theta *= pi / 180;
    double ct = Math.cos(theta);
    double st = Math.sin(theta);

    double Nyx = (yx * ct + xx * st);
    double Nyy = (yy * ct + xy * st);
    double Nyz = (yz * ct + xz * st);
    double Nyo = (yo * ct + xo * st);

    double Nxx = (xx * ct - yx * st);
    double Nxy = (xy * ct - yy * st);
    double Nxz = (xz * ct - yz * st);
    double Nxo = (xo * ct - yo * st);

    yo = Nyo;
    yx = Nyx;
    yy = Nyy;
    yz = Nyz;
    xo = Nxo;
    xx = Nxx;
    xy = Nxy;
    xz = Nxz;
  }
Example #17
0
  /** Rotate theta degrees around the y axis */
  void yrot(double theta) {
    theta *= (pi / 180);
    double ct = Math.cos(theta);
    double st = Math.sin(theta);

    double Nxx = (xx * ct + zx * st);
    double Nxy = (xy * ct + zy * st);
    double Nxz = (xz * ct + zz * st);
    double Nxo = (xo * ct + zo * st);

    double Nzx = (zx * ct - xx * st);
    double Nzy = (zy * ct - xy * st);
    double Nzz = (zz * ct - xz * st);
    double Nzo = (zo * ct - xo * st);

    xo = Nxo;
    xx = Nxx;
    xy = Nxy;
    xz = Nxz;
    zo = Nzo;
    zx = Nzx;
    zy = Nzy;
    zz = Nzz;
  }
 public double evaluate(double x) {
   return Math.log(x * x + 1) - Math.exp(0.4 * x) * Math.cos(Math.PI * x);
 }
Example #19
0
 private int yCor(int len, double dir) {
   return (int) (len * Math.cos(dir));
 }
 public double evaluate_1(double x) {
   return (2 * x / x * x + 1)
       - 0.4 * Math.exp(0.4 * x) * Math.cos(Math.PI * x)
       + Math.PI * Math.exp(0.4 * x) * Math.sin(Math.PI * x);
 }
Example #21
0
  public MapPanel(ClientGameBoard gl) {
    super();

    _dismiss = false;
    gameLogic = gl;
    gameLogic._mapPanel = this;
    _hexes = new ArrayList<Hex>();
    vertexContents = new Hashtable<CoordPair, Pair>();
    roadContents = new Hashtable<Pair, Integer>();
    portContents = new Hashtable<Pair, BoardObject.type>();

    diceImage = new BufferedImage(582, 98, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = diceImage.createGraphics();
    g.drawImage(BoardObject.images.get(BoardObject.type.DICE), null, null);
    g.dispose();

    rings = gameLogic.getNumRings();

    hexleft =
        100
            - (int)
                (radius
                    + (Math.floor(rings / 2) * radius + Math.floor((rings - 1) / 2) * radius * 2));
    if (rings % 2 == 0) {
      hexleft -= radius / 2;
    }

    hextop = 300 - (int) (radius * 0.866 + (rings - 1) * 2 * (radius * 0.866));

    double border = 0.4;

    HashMap<Pair, Pair> hexData = gameLogic.getHexInfo(); // call the gamelogic

    Pair currCoord = gameLogic.getStartPoint();

    Pair topCoord = currCoord;

    int ring = 0;

    int currentDir = 5;
    int current = 0;
    int[][] directions = {{1, 1}, {0, 2}, {-1, 1}, {-1, -1}, {0, -2}, {1, -1}};

    int[][] HexCoordDirections = {{2, 1}, {0, 2}, {-2, 1}, {-2, -1}, {0, -2}, {2, -1}};

    Hex top =
        new Hex(
            100,
            300,
            radius,
            (BoardObject.type) (hexData.get(currCoord).getA()),
            (Integer) (hexData.get(currCoord).getB()));
    Hex curr = top;

    _hexes.add(top);
    while (true) {
      if (current == ring) {
        currentDir++;
        current = 0;
      }
      if (currentDir > 5) {
        currentDir = 0;
        current = 0;
        ring++;
        if (ring < rings) {
          topCoord = new Pair(currCoord.getA(), (Double) (currCoord.getB()) - 2);
          currCoord = topCoord;

          top =
              new Hex(
                  curr.getX(),
                  (curr.getY() - 2 * (Math.cos(Math.PI / 6) * (curr.getRadius() + border))),
                  curr.getRadius(),
                  (BoardObject.type) (hexData.get(currCoord).getA()),
                  (Integer) (hexData.get(currCoord).getB()));
          curr = top;

        } else {
          break;
        }
      }
      currCoord.setA((Object) ((Double) (currCoord.getA()) + HexCoordDirections[currentDir][0]));
      currCoord.setB((Object) ((Double) (currCoord.getB()) + HexCoordDirections[currentDir][1]));

      curr =
          new Hex(
              (curr.getX() + directions[currentDir][0] * (curr.getRadius() + border) * 3 / 2),
              (curr.getY()
                  + directions[currentDir][1]
                      * (Math.cos(Math.PI / 6) * (curr.getRadius() + border))),
              curr.getRadius(),
              (BoardObject.type) (hexData.get(currCoord).getA()),
              (Integer) (hexData.get(currCoord).getB()));
      _hexes.add(curr);

      current++;
    }

    addMouseListener(this);
    addMouseMotionListener(this);
  }
  public void Hough() {
    // for polar we need accumulator of 180degress * the longest length in the image
    // rmax = (int)Math.sqrt(width*width + height*height);

    System.out.println("w: " + width + " h: " + height + " rmax: " + rmax);
    acc = new int[width * height][accRMax];
    int rOffset;
    for (int x = 0; x < height; x++) {
      for (int y = 0; y < width; y++) {
        rOffset = 0;
        for (int r = rmin; r < rmax; r += offset) {
          acc[x * width + y][rOffset++] = 0;
        }
      }
    }
    System.out.println("accumulating");
    int x0, y0;
    double t;
    int[] val = new int[1];
    for (int x = 0; x < width; x++) {
      for (int y = 0; y < height; y++) {

        // if ((nonMax.getRaster().getPixel(x, y, val)[0])== -1) {
        if ((data[y * width + x] & 0xFF) == 255) {
          rOffset = 0;
          for (int r = rmin; r < rmax; r += offset) {
            for (int theta = 0; theta < 360; theta += 2) {
              t = (theta * 3.14159265) / 180;
              x0 = (int) Math.round(x - r * Math.cos(t));
              y0 = (int) Math.round(y - r * Math.sin(t));
              if (x0 < width && x0 > 0 && y0 < height && y0 > 0) {
                acc[x0 + (y0 * width)][rOffset] += 1;
              }
            }
            rOffset++;
          }
        }
      }
    }
    // now normalise to 255 and put in format for a pixel array
    int max = 0;
    // Find max acc value
    System.out.println("Finding Max");
    for (int x = 0; x < width; x++) {
      for (int y = 0; y < height; y++) {
        rOffset = 0;
        for (int r = rmin; r < rmax; r += offset) {
          if (acc[x + (y * width)][rOffset] > max) {
            max = acc[x + (y * width)][rOffset];
          }
          rOffset++;
        }
      }
    }

    // Normalise all the values
    int value;
    System.out.println("Normalising");
    for (int x = 0; x < width; x++) {
      for (int y = 0; y < height; y++) {
        rOffset = 0;
        for (int r = rmin; r < rmax; r += offset) {
          value = (int) (((double) acc[x + (y * width)][rOffset] / (double) max) * 255.0);
          acc[x + (y * width)][rOffset] = 0xff000000 | (value << 16 | value << 8 | value);
          rOffset++;
        }
      }
    }

    findMaxima();

    System.out.println("done");
  }
  public synchronized void drag_direct(VisADRay ray, boolean first, int mouseModifiers) {
    if (barbValues == null || ref == null || shadow == null) return;

    if (first) {
      stop = false;
    } else {
      if (stop) return;
    }

    // modify direction if mshift != 0
    // modify speed if mctrl != 0
    // modify speed and direction if neither
    int mshift = mouseModifiers & InputEvent.SHIFT_MASK;
    int mctrl = mouseModifiers & InputEvent.CTRL_MASK;

    float o_x = (float) ray.position[0];
    float o_y = (float) ray.position[1];
    float o_z = (float) ray.position[2];
    float d_x = (float) ray.vector[0];
    float d_y = (float) ray.vector[1];
    float d_z = (float) ray.vector[2];

    if (pickCrawlToCursor) {
      if (first) {
        offset_count = OFFSET_COUNT_INIT;
      } else {
        if (offset_count > 0) offset_count--;
      }
      if (offset_count > 0) {
        float mult = ((float) offset_count) / ((float) OFFSET_COUNT_INIT);
        o_x += mult * offsetx;
        o_y += mult * offsety;
        o_z += mult * offsetz;
      }
    }

    if (first || refirst) {
      point_x = barbValues[2];
      point_y = barbValues[3];
      point_z = 0.0f;
      line_x = 0.0f;
      line_y = 0.0f;
      line_z = 1.0f; // lineAxis == 2 in DataRenderer.drag_direct
    } // end if (first || refirst)

    float[] x = new float[3]; // x marks the spot
    // DirectManifoldDimension = 2
    // intersect ray with plane
    float dot = (point_x - o_x) * line_x + (point_y - o_y) * line_y + (point_z - o_z) * line_z;
    float dot2 = d_x * line_x + d_y * line_y + d_z * line_z;
    if (dot2 == 0.0) return;
    dot = dot / dot2;
    // x is intersection
    x[0] = o_x + dot * d_x;
    x[1] = o_y + dot * d_y;
    x[2] = o_z + dot * d_z;
    /*
    System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
    */
    try {

      Tuple data = (Tuple) link.getData();
      int n = ((TupleType) data.getType()).getNumberOfRealComponents();
      Real[] reals = new Real[n];

      int k = 0;
      int m = data.getDimension();
      for (int i = 0; i < m; i++) {
        Data component = data.getComponent(i);
        if (component instanceof Real) {
          reals[k++] = (Real) component;
        } else if (component instanceof RealTuple) {
          for (int j = 0; j < ((RealTuple) component).getDimension(); j++) {
            reals[k++] = (Real) ((RealTuple) component).getComponent(j);
          }
        }
      }

      if (first || refirst) {
        // get first Data flow vector
        for (int i = 0; i < 3; i++) {
          int j = flowToComponent[i];
          data_flow[i] = (j >= 0) ? (float) reals[j].getValue() : 0.0f;
        }

        if (coord != null) {
          float[][] ds = {{data_flow[0]}, {data_flow[1]}, {data_flow[2]}};
          ds = coord.toReference(ds);
          data_flow[0] = ds[0][0];
          data_flow[1] = ds[1][0];
          data_flow[2] = ds[2][0];
        }

        data_speed =
            (float)
                Math.sqrt(
                    data_flow[0] * data_flow[0]
                        + data_flow[1] * data_flow[1]
                        + data_flow[2] * data_flow[2]);
        float barb0 = barbValues[2] - barbValues[0];
        float barb1 = barbValues[3] - barbValues[1];
        /*
        System.out.println("data_flow = " + data_flow[0] + " " + data_flow[1] +
                           " " + data_flow[2]);
        System.out.println("barbValues = " + barbValues[0] + " " + barbValues[1] +
                           "   " + barbValues[2] + " " + barbValues[3]);
        System.out.println("data_speed = " + data_speed);
        */
      } // end if (first || refirst)

      // convert x to a flow vector, and from spatial to earth
      if (getRealVectorTypes(which_barb) instanceof EarthVectorType) {
        // don't worry about vector magnitude -
        // data_speed & display_speed take care of that
        float eps = 0.0001f; // estimate derivative with a little vector
        float[][] spatial_locs = {
          {barbValues[0], barbValues[0] + eps * (x[0] - barbValues[0])},
          {barbValues[1], barbValues[1] + eps * (x[1] - barbValues[1])},
          {0.0f, 0.0f}
        };
        /*
        System.out.println("spatial_locs = " + spatial_locs[0][0] + " " +
                           spatial_locs[0][1] + " " + spatial_locs[1][0] + " " +
                           spatial_locs[1][1]);
        */
        float[][] earth_locs = spatialToEarth(spatial_locs);
        // WLH - 18 Aug 99
        if (earth_locs == null) return;
        /*
        System.out.println("earth_locs = " + earth_locs[0][0] + " " +
                           earth_locs[0][1] + " " + earth_locs[1][0] + " " +
                           earth_locs[1][1]);
        */
        x[2] = 0.0f;
        x[0] =
            (earth_locs[1][1] - earth_locs[1][0])
                * ((float) Math.cos(Data.DEGREES_TO_RADIANS * earth_locs[0][0]));
        x[1] = earth_locs[0][1] - earth_locs[0][0];
        /*
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else { // if (!(getRealVectorTypes(which_barb) instanceof EarthVectorType))
        // convert x to vector
        x[0] -= barbValues[0];
        x[1] -= barbValues[1];

        // adjust for spatial map scalings but don't worry about vector
        // magnitude - data_speed & display_speed take care of that
        // also, spatial is Cartesian
        double[] ranges = getRanges();
        for (int i = 0; i < 3; i++) {
          x[i] /= ranges[i];
        }
        /*
        System.out.println("ranges = " + ranges[0] + " " + ranges[1] +
                           " " + ranges[2]);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      }

      // WLH 6 August 99
      x[0] = -x[0];
      x[1] = -x[1];
      x[2] = -x[2];

      /* may need to do this for performance
            float[] xx = {x[0], x[1], x[2]};
            addPoint(xx);
      */

      float x_speed = (float) Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
      /* WLH 16 April 2002 - from Ken
            if (x_speed < 0.000001f) x_speed = 0.000001f;
      */
      if (x_speed < 0.01f) x_speed = 0.01f;
      if (first || refirst) {
        display_speed = x_speed;
      }
      refirst = false;

      if (mshift != 0) {
        // only modify data_flow direction
        float ratio = data_speed / x_speed;
        x[0] *= ratio;
        x[1] *= ratio;
        x[2] *= ratio;
        /*
        System.out.println("direction, ratio = " + ratio + " " +
                           data_speed + " " + x_speed);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else if (mctrl != 0) {
        // only modify data_flow speed
        float ratio = x_speed / display_speed;
        if (data_speed < EPS) {
          data_flow[0] = 2.0f * EPS;
          refirst = true;
        }
        x[0] = ratio * data_flow[0];
        x[1] = ratio * data_flow[1];
        x[2] = ratio * data_flow[2];
        /*
        System.out.println("speed, ratio = " + ratio + " " +
                           x_speed + " " + display_speed);
        System.out.println("x = " + x[0] + " " + x[1] + " " + x[2]);
        */
      } else {
        // modify data_flow speed and direction
        float ratio = data_speed / display_speed;
        /*
        System.out.println("data_speed = " + data_speed +
                           " display_speed = " + display_speed +
                           " ratio = " + ratio + " EPS = " + EPS);
        System.out.println("x = " + x[0] + " " + x[1] +" " + x[2] +
                           " x_speed = " + x_speed);
          data_speed = 21.213203 display_speed = 0.01 ratio = 2121.3203 EPS = 0.2
          x = 1.6170928E-4 1.6021729E-4 -0.0 x_speed = 0.01
          wind = (0.3430372, 0.33987218) at (-35.0, 5.0)
        */
        if (data_speed < EPS) {
          data_flow[0] = 2.0f * EPS;
          x[0] = data_flow[0];
          x[1] = data_flow[1];
          x[2] = data_flow[2];
          refirst = true;
        } else {
          x[0] *= ratio;
          x[1] *= ratio;
          x[2] *= ratio;
        }
      }

      if (coord != null) {
        float[][] xs = {{x[0]}, {x[1]}, {x[2]}};
        xs = coord.fromReference(xs);
        x[0] = xs[0][0];
        x[1] = xs[1][0];
        x[2] = xs[2][0];
      }

      // now replace flow values
      Vector vect = new Vector();
      for (int i = 0; i < 3; i++) {
        int j = flowToComponent[i];
        if (j >= 0) {
          RealType rtype = (RealType) reals[j].getType();
          reals[j] = new Real(rtype, (double) x[i], rtype.getDefaultUnit(), null);

          // WLH 31 Aug 2000
          Real r = reals[j];
          Unit overrideUnit = null;
          if (directMap[i] != null) {
            overrideUnit = directMap[i].getOverrideUnit();
          }
          Unit rtunit = rtype.getDefaultUnit();
          // units not part of Time string
          if (overrideUnit != null
              && !overrideUnit.equals(rtunit)
              && !RealType.Time.equals(rtype)) {
            double d = (float) overrideUnit.toThis((double) x[0], rtunit);
            r = new Real(rtype, d, overrideUnit);
            String valueString = r.toValueString();
            vect.addElement(rtype.getName() + " = " + valueString);
          } else {
            // create location string
            vect.addElement(rtype.getName() + " = " + x[i]);
          }
        }
      }
      getDisplayRenderer().setCursorStringVector(vect);

      Data newData = null;
      // now build new RealTuple or Flat Tuple
      if (data instanceof RealTuple) {
        newData =
            new RealTuple(
                ((RealTupleType) data.getType()), reals, ((RealTuple) data).getCoordinateSystem());
      } else {
        Data[] new_components = new Data[m];
        k = 0;
        for (int i = 0; i < m; i++) {
          Data component = data.getComponent(i);
          if (component instanceof Real) {
            new_components[i] = reals[k++];
          } else if (component instanceof RealTuple) {
            Real[] sub_reals = new Real[((RealTuple) component).getDimension()];
            for (int j = 0; j < ((RealTuple) component).getDimension(); j++) {
              sub_reals[j] = reals[k++];
            }
            new_components[i] =
                new RealTuple(
                    ((RealTupleType) component.getType()),
                    sub_reals,
                    ((RealTuple) component).getCoordinateSystem());
          }
        }
        newData = new Tuple(new_components, false);
      }
      ref.setData(newData);
    } catch (VisADException e) {
      // do nothing
      System.out.println("drag_direct " + e);
      e.printStackTrace();
    } catch (RemoteException e) {
      // do nothing
      System.out.println("drag_direct " + e);
      e.printStackTrace();
    }
  }
 void step() {
   turtle_x += turtle_r * Math.cos(turtle_theta * 0.017453292);
   turtle_y += turtle_r * Math.sin(turtle_theta * 0.017453292);
 }
Example #25
0
  public void simulateBall() {
    ballPreviousX = ballX;
    ballPreviousY = ballY;
    leftEdgeActive = rightEdgeActive = topEdgeActive = bottomEdgeActive = true;

    if (ballY >= MaxY) {
      ballStarted = false;
    }

    if (!ballStarted) {
      ballX = padx - ballDiameter / 2;
      ballY = padTop - ballDiameter;
    } else {
      ballX = ballX + (int) (Math.cos((angle * pi) / 180.0) * unit);
      ballY = ballY - (int) (Math.sin((angle * pi) / 180.0) * unit); // Y increases downward
      if (Math.sin((angle * pi) / 180.0) * unit >= 0) {
        top = true;
      } else top = false;

      if (Math.cos((angle * pi) / 180.0) * unit >= 0) {
        right = true;
      } else right = false;

      if (right) leftEdgeActive = false;
      else rightEdgeActive = false;

      if (top) bottomEdgeActive = false;
      else topEdgeActive = false;

      Pair temp;

      if (leftEdgeActive) {
        int xBlockLeft = ((ballX - blockStartX) / blockLength) * blockLength;
        int yBlockLeft = ((ballY - blockStartY + ballDiameter / 2) / blockHeight) * blockHeight;

        // Left Boundary Edge
        temp = new Pair(xBlockLeft, yBlockLeft);
        if ((blockMap.containsKey(temp.toString())
                && (ballX >= blockStartX)
                && (ballY >= blockStartY))
            || ballX <= 0) {
          if (immutableBlocks.containsKey(temp.toString()) == false) {

            /*				if(fireBlocks.containsKey(temp.toString())){
            				fireEnabled = true;
            			}
            */
            angle = 180.0 - angle;
            blockMap.remove(temp.toString());
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            return;
          } else {
            // angle = 180.0 - angle;
            blockMap.put(temp.toString(), Color.RED);
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            return;
          }
        }
      }

      if (rightEdgeActive) {
        int xBlockRight = ((ballX - blockStartX + ballDiameter) / blockLength) * blockLength;
        int yBlockRight = ((ballY - blockStartY + ballDiameter / 2) / blockHeight) * blockHeight;
        // Right Boundary Edge
        temp = new Pair(xBlockRight, yBlockRight);
        if ((blockMap.containsKey(temp.toString())
                && (ballX - blockStartX + ballDiameter > 0)
                && (ballY - blockStartY + ballDiameter / 2) >= 0)
            || (ballX + ballDiameter) >= MaxX) {
          // System.out.println("Right edge");
          if (immutableBlocks.containsKey(temp.toString()) == false) {
            /*		if(fireBlocks.containsKey(temp.toString())){
            	fireEnabled = true;
            }*/
            angle = 180.0 - angle;
            blockMap.remove(temp.toString());
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            return;
          } else {
            // angle = 180.0 - angle;
            blockMap.put(temp.toString(), Color.RED);
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            return;
          }
        }
      }
      if (topEdgeActive) {
        int xBlockTop = ((ballX - blockStartX + ballDiameter / 2) / blockLength) * blockLength;
        int yBlockTop = ((ballY - blockStartY) / blockHeight) * blockHeight;
        // top Boundary Edge
        temp = new Pair(xBlockTop, yBlockTop);

        if ((blockMap.containsKey(temp.toString())
                && (ballX >= blockStartX)
                && (ballY >= blockStartY))
            || (ballY - ballDiameter) <= 0) {
          if (immutableBlocks.containsKey(temp.toString()) == false) {
            /*if(fireBlocks.containsKey(temp.toString())){
            		fireEnabled = true;
            }*/

            angle = 360.0 - angle;
            blockMap.remove(temp.toString());
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            // System.out.println("temp " + temp.toString());

            return;
          } else {
            // angle = 360.0 - angle;
            blockMap.put(temp.toString(), Color.RED);
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            return;
          }
        }
      }
      if (bottomEdgeActive) {
        int xBlockBottom = ((ballX - blockStartX + ballDiameter / 2) / blockLength) * blockLength;
        int yBlockBottom = ((ballY - blockStartY + ballDiameter) / blockHeight) * blockHeight;
        // top Boundary Edge
        temp = new Pair(xBlockBottom, yBlockBottom);
        if ((blockMap.containsKey(temp.toString())
                && (ballX - blockStartX + ballDiameter / 2 >= 0)
                && (ballY - blockStartY + ballDiameter >= 0))
            || (((((ballY + ballDiameter) >= padTop && (ballY + ballDiameter) <= padBottom))
                    || (ballY >= padTop && ballY <= padBottom))
                && (ballX) >= (padx - padLength / 2)
                && ballX <= (padx + padLength / 2))) {

          if (immutableBlocks.containsKey(temp.toString()) == false) {
            /*if(fireBlocks.containsKey(temp.toString())){
            	fireEnabled = true;
            }*/
            angle = 360.0 - angle;
            blockMap.remove(temp.toString());
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            return;
          } else {
            // angle = 360.0 - angle;
            blockMap.put(temp.toString(), Color.RED);
            repaintBlocks = true;
            count = numRepaints;
            repaint();
            return;
          }
        }
      }
    }
  }
 public void move() {
   objtimer++;
   // move
   if (xmot.random && objtimer % (int) (35 * xmot.randomchg) == 0) {
     xspeed = xmot.speed * random(-1, 1, 2);
   }
   if (ymot.random && objtimer % (int) (35 * ymot.randomchg) == 0) {
     yspeed = ymot.speed * random(-1, 1, 2);
   }
   if (player != null) {
     double playerdist =
         Math.sqrt((player.x - x) * (player.x - x) + (player.y - y) * (player.y - y))
             * 100.0
             / (pfWidth());
     if (xmot.toplayer && playerdist > xmot.toplayermin && playerdist < xmot.toplayermax) {
       xspeed = 0;
       x += xmot.speed * (player.x > x ? 1 : -1);
     } else if (xmot.frplayer
         && playerdist > xmot.frplayermin
         && playerdist < xmot.frplayermax) {
       xspeed = 0;
       x += xmot.speed * (player.x < x ? 1 : -1);
     }
     if (ymot.toplayer && playerdist > ymot.toplayermin && playerdist < ymot.toplayermax) {
       yspeed = 0;
       y += ymot.speed * (player.y > y ? 1 : -1);
     } else if (ymot.frplayer
         && playerdist > ymot.frplayermin
         && playerdist < ymot.frplayermax) {
       yspeed = 0;
       y += ymot.speed * (player.y < y ? 1 : -1);
     }
   }
   // react to background
   int bounces = 0;
   if (bouncesides.equals("any")) {
     bounces |= 15;
   } else if (bouncesides.equals("top")) {
     bounces |= 1;
   } else if (bouncesides.equals("bottom")) {
     bounces |= 2;
   } else if (bouncesides.equals("topbottom")) {
     bounces |= 3;
   } else if (bouncesides.equals("left")) {
     bounces |= 4;
   } else if (bouncesides.equals("right")) {
     bounces |= 8;
   } else if (bouncesides.equals("leftright")) {
     bounces |= 12;
   }
   if ((bounces & 1) != 0 && y < 0) {
     y = 0;
     if (yspeed < 0) yspeed = -yspeed;
   }
   if ((bounces & 2) != 0 && y > pfHeight() - 16) {
     y = pfHeight() - 16;
     if (yspeed > 0) yspeed = -yspeed;
   }
   if ((bounces & 4) != 0 && x < 0) {
     x = 0;
     if (xspeed < 0) xspeed = -xspeed;
   }
   if ((bounces & 8) != 0 && x > pfWidth() - 16) {
     x = pfWidth() - 16;
     if (xspeed > 0) xspeed = -xspeed;
   }
   // shoot
   if (shoot && shootfreq > 0.0 && objtimer % (int) (shootfreq * 35) == 0) {
     if (shootdir.equals("left")) {
       new AgentBullet(x, y, bullettype, sprite, diebgtype | blockbgtype, -shootspeed, 0);
     } else if (shootdir.equals("right")) {
       new AgentBullet(x, y, bullettype, sprite, diebgtype | blockbgtype, shootspeed, 0);
     } else if (shootdir.equals("up")) {
       new AgentBullet(x, y, bullettype, sprite, diebgtype | blockbgtype, 0, -shootspeed);
     } else if (shootdir.equals("down")) {
       new AgentBullet(x, y, bullettype, sprite, diebgtype | blockbgtype, 0, shootspeed);
     } else if (shootdir.equals("player") && player != null) {
       double angle = Math.atan2(player.x - x, player.y - y);
       new AgentBullet(
           x,
           y,
           bullettype,
           sprite,
           diebgtype | blockbgtype,
           shootspeed * Math.sin(angle),
           shootspeed * Math.cos(angle));
     }
   }
 }
Example #27
0
  void EstimateDrawTime() {
    int i, j;

    float drawScale = 1.0f;
    double px = 0, py = 0, pz = 0;
    float feed_rate = 1.0f;

    estimated_time = 0;
    float estimated_length = 0;
    int estimate_count = 0;

    for (i = 0; i < gcode.size(); ++i) {
      String line = gcode.get(i);
      String[] pieces = line.split(";");
      if (pieces.length == 0) continue;

      String[] tokens = pieces[0].split("\\s");
      if (tokens.length == 0) continue;

      for (j = 0; j < tokens.length; ++j) {
        if (tokens[j].equals("G20")) drawScale = 0.393700787f;
        if (tokens[j].equals("G21")) drawScale = 0.1f;
        if (tokens[j].startsWith("F")) {
          feed_rate = Float.valueOf(tokens[j].substring(1)) * drawScale;
          Log("<span style='color:green'>feed rate=" + feed_rate + "</span>\n");
          feed_rate *= 1;
        }
      }

      double x = px;
      double y = py;
      double z = pz;
      double ai = px;
      double aj = py;
      for (j = 1; j < tokens.length; ++j) {
        if (tokens[j].startsWith("X")) x = Float.valueOf(tokens[j].substring(1)) * drawScale;
        if (tokens[j].startsWith("Y")) y = Float.valueOf(tokens[j].substring(1)) * drawScale;
        if (tokens[j].startsWith("Z")) z = Float.valueOf(tokens[j].substring(1)) * drawScale;
        if (tokens[j].startsWith("I")) ai = px + Float.valueOf(tokens[j].substring(1)) * drawScale;
        if (tokens[j].startsWith("J")) aj = py + Float.valueOf(tokens[j].substring(1)) * drawScale;
      }

      if (tokens[0].equals("G00")
          || tokens[0].equals("G0")
          || tokens[0].equals("G01")
          || tokens[0].equals("G1")) {
        // draw a line
        double ddx = x - px;
        double ddy = y - py;
        double dd = Math.sqrt(ddx * ddx + ddy * ddy);
        estimated_time += dd / feed_rate;
        estimated_length += dd;
        ++estimate_count;
        px = x;
        py = y;
        pz = z;
      } else if (tokens[0].equals("G02")
          || tokens[0].equals("G2")
          || tokens[0].equals("G03")
          || tokens[0].equals("G3")) {
        // draw an arc
        int dir = (tokens[0].equals("G02") || tokens[0].equals("G2")) ? -1 : 1;
        double dx = px - ai;
        double dy = py - aj;
        double radius = Math.sqrt(dx * dx + dy * dy);

        // find angle of arc (sweep)
        double angle1 = atan3(dy, dx);
        double angle2 = atan3(y - aj, x - ai);
        double theta = angle2 - angle1;

        if (dir > 0 && theta < 0) angle2 += 2.0 * Math.PI;
        else if (dir < 0 && theta > 0) angle1 += 2.0 * Math.PI;

        theta = Math.abs(angle2 - angle1);

        // Draw the arc from a lot of little line segments.
        for (int k = 0; k <= theta * DrawPanel.STEPS_PER_DEGREE; ++k) {
          double angle3 =
              (angle2 - angle1) * ((double) k / (theta * DrawPanel.STEPS_PER_DEGREE)) + angle1;
          float nx = (float) (ai + Math.cos(angle3) * radius);
          float ny = (float) (aj + Math.sin(angle3) * radius);

          double ddx = nx - px;
          double ddy = ny - py;
          double dd = Math.sqrt(ddx * ddx + ddy * ddy);
          estimated_time += dd / feed_rate;
          estimated_length += dd;
          ++estimate_count;
          px = nx;
          py = ny;
        }
        double ddx = x - px;
        double ddy = y - py;
        double dd = Math.sqrt(ddx * ddx + ddy * ddy);
        estimated_time += dd / feed_rate;
        estimated_length += dd;
        ++estimate_count;
        px = x;
        py = y;
        pz = z;
      }
    } // for ( each instruction )
    estimated_time += estimate_count * 0.007617845117845f;

    Log(
        "<font color='green'>"
            + estimate_count
            + " line segments.\n"
            + estimated_length
            + "cm of line.\n"
            + "Estimated "
            + statusBar.formatTime((long) (estimated_time * 10000))
            + "s to draw.</font>\n");
  }