Exemple #1
1
  public void run() {
    String[] sData;
    while (oConn.isConnected()) {
      sData = oConn.getData();
      System.out.println("Received \"" + sData[0] + "\" command.");

      if (sData[0].equals("chat")) panChat.addChat(sData[1]);
      else if (sData[0].equals("loadmap")) {
        try {
          oMap.loadMap(new File(DEFAULT_MAP_DIRECTORY + sData[1]));
          int nRand = (int) Math.floor((Math.random() + 1) + 0.5);
          stateDeploy(nRand);
          if (nRand == 1) nRand = 2;
          else nRand = 1;
          oConn.send("deploy", "" + nRand);
        } catch (FileNotFoundException e) {
          oConn.send("error", "Opponent does not have map.");
          actionDisconnect();
        }
      } else if (sData[0].equals("deploy")) {
        stateDeploy(Integer.parseInt(sData[1]));
      } else if (sData[0].equals("error")) {
        JOptionPane.showMessageDialog(frame, sData[1]);
        actionDisconnect();
      } else if (sData[0].equals("deployed")) {
        bOpponentDeployed = true;
        if (bDeployed) {
          oConn.send("trade parties", "");
          tradeParties();
          makeAvatarOrder();
          long nRandSeed = Math.round((Math.random() * Long.MAX_VALUE));
          oRandom = new Random(nRandSeed);
          oConn.send("random seed", "" + nRandSeed);
          oConn.send("phase", "1");
          phase1();
        }
      } else if (sData[0].equals("trade parties")) {
        tradeParties();
      } else if (sData[0].equals("avatar order")) {
        makeAvatarOrder(sData[1]);
      } else if (sData[0].equals("random seed")) {
        oRandom = new Random(Long.parseLong(sData[1]));
      } else if (sData[0].equals("phase")) {
        switch (Integer.parseInt(sData[1])) {
          case 1:
            phase1();
            break;
          case 2:
            phase2();
            break;
          case 3:
            phase3();
            break;
          case 4:
            iChar = 0;
            bMyAT = false;
            phase4();
            break;
        }
      } else if (sData[0].equals("move")) {
        oMap.moveATAvatar(Integer.parseInt(sData[1]), Integer.parseInt(sData[2]));
        // TEMP
        stateEndTurn();
      }
    }
  }
Exemple #2
0
  public void fitSpline(int evaluationPoints) {
    if (xpf == null) {
      xpf = toFloat(xp);
      ypf = toFloat(yp);
      subPixel = true;
    }
    if (xSpline == null || splinePoints != evaluationPoints) {
      splinePoints = evaluationPoints;
      xSpline = new float[splinePoints];
      ySpline = new float[splinePoints];
    }
    int nNodes = nPoints;
    if (type == POLYGON) {
      nNodes++;
      if (nNodes >= xpf.length) enlargeArrays();
      xpf[nNodes - 1] = xpf[0];
      ypf[nNodes - 1] = ypf[0];
    }
    float[] xindex = new float[nNodes];
    for (int i = 0; i < nNodes; i++) xindex[i] = i;
    SplineFitter sfx = new SplineFitter(xindex, xpf, nNodes);
    SplineFitter sfy = new SplineFitter(xindex, ypf, nNodes);

    // Evaluate the splines at all points
    double scale = (double) (nNodes - 1) / (splinePoints - 1);
    float xs = 0f, ys = 0f;
    float xmin = Float.MAX_VALUE, xmax = -xmin, ymin = xmin, ymax = xmax;
    for (int i = 0; i < splinePoints; i++) {
      double xvalue = i * scale;
      xs = (float) sfx.evalSpline(xindex, xpf, nNodes, xvalue);
      if (xs < xmin) xmin = xs;
      if (xs > xmax) xmax = xs;
      xSpline[i] = xs;
      ys = (float) sfy.evalSpline(xindex, ypf, nNodes, xvalue);
      if (ys < ymin) ymin = ys;
      if (ys > ymax) ymax = ys;
      ySpline[i] = ys;
    }
    int ixmin = (int) Math.floor(xmin + 0.5f);
    int ixmax = (int) Math.floor(xmax + 0.5f);
    int iymin = (int) Math.floor(ymin + 0.5f);
    int iymax = (int) Math.floor(ymax + 0.5f);
    if (ixmin != 0) {
      for (int i = 0; i < nPoints; i++) xpf[i] -= ixmin;
      for (int i = 0; i < splinePoints; i++) xSpline[i] -= ixmin;
    }
    if (iymin != 0) {
      for (int i = 0; i < nPoints; i++) ypf[i] -= iymin;
      for (int i = 0; i < splinePoints; i++) ySpline[i] -= iymin;
    }
    x += ixmin;
    y += iymin;
    width = ixmax - ixmin;
    height = iymax - iymin;
    bounds = null;
    cachedMask = null;
    // update protected xp and yp arrays for backward compatibility
    xp = toInt(xpf, xp, nPoints);
    yp = toInt(ypf, yp, nPoints);
  }
Exemple #3
0
  /**
   * Draw the LineSelection at its current location. It is the responsibility of the
   * applet/application to draw the LineSelection at the appropriate times, e.g., inside the
   * component's update() and/or paint() method. This gives maximum flexibility for double
   * buffering, etc.
   *
   * @param g The Graphics context to use for drawing.
   */
  public void draw(Graphics g) {

    if (!isVisible()) {
      return;
    }

    Color saveColor = g.getColor();
    g.setColor(color);
    if (thickness > 1) {
      double ratio = ((double) thickness) / ((double) length());
      double txdb = ratio * ((double) height) / 2.0;
      int tx = txdb > 0 ? ((int) Math.ceil(txdb)) : ((int) Math.floor(txdb));
      double tydb = -ratio * ((double) width) / 2.0;
      int ty = tydb > 0 ? ((int) Math.ceil(tydb)) : ((int) Math.floor(tydb));
      Point[] poly = new Point[4];
      for (int i = 0; i < 4; i++) poly[i] = new Point(x, y);
      poly[0].translate(tx, ty);
      poly[1].translate(-tx, -ty);
      poly[2].translate(width, height);
      poly[2].translate(-tx, -ty);
      poly[3].translate(width, height);
      poly[3].translate(tx, ty);
      Polygon polygon = new Polygon();
      for (int i = 0; i < 4; i++) polygon.addPoint(poly[i].x, poly[i].y);
      g.fillPolygon(polygon);
    } else g.drawLine(x, y, x + width, y + height);
    g.setColor(saveColor);
  } // end draw
Exemple #4
0
  /** Precompute number of ticks */
  public static int calculateTicNumber(
      double ticMinVal, double ticMaxVal, double xStep, boolean isLog) {

    int n = 0;

    // System.out.println("\n-- calculateTicNumber=");
    // System.out.println("Min="+Double.toString(ticMinVal));
    // System.out.println("Max="+Double.toString(ticMaxVal));
    // System.out.println("Max="+Double.toString(xStep));

    if (isLog == false) {
      double xStart = xStep * Math.ceil(ticMinVal / xStep);
      for (double xpos = xStart; xpos <= ticMaxVal; xpos += xStep) n++;
    } else {
      int t1 = 0;
      int t2 = 0;
      if (ticMinVal > 0) t1 = (int) Math.floor(log10(ticMinVal) - 0.5);
      if (ticMinVal < 0) t1 = -1 * (int) Math.floor(log10(-1 * ticMinVal) - 0.5);
      if (ticMaxVal > 0) t2 = (int) Math.floor(log10(ticMaxVal) + 1.0);
      if (ticMaxVal < 0) t2 = -1 * (int) Math.floor(log10(-1 * ticMaxVal) + 1.0);
      for (int i = t1; i < t2 + 1; i++) n++;
    }

    // System.out.println("Nr of ticks="+Integer.toString(n));

    return n;
  }
Exemple #5
0
  public boolean transform(ProgressListener progressListener) {

    toneMap = toneMapFrame.getToneMap();
    timeSet = toneMap.getTimeSet();
    pitchSet = toneMap.getPitchSet();
    timeRange = timeSet.getRange();
    pitchRange = pitchSet.getRange();

    pitchFreqSet = pitchSet.getFreqSet();
    audioFTPower = new double[timeRange * (pitchRange + 1)];

    int startSample = timeSet.getStartSample();
    int endSample = timeSet.getEndSample();
    int sampleLength = (int) Math.floor((endSample - startSample) / ((double) resolution));
    double[] audioSamples = new double[sampleLength];

    for (int i = 0; i < sampleLength; i++) {
      audioSamples[i] = (double) audioData[startSample + i * resolution];
    }

    int sampleIndexSize =
        (int) Math.floor((double) timeSet.getSampleIndexSize() / (double) resolution);

    double dt = (double) resolution / sampleRate;
    if (transformMode == TRANSFORM_MODE_JAVA) {
      wavelet.convert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    } else {

      WaveletJNI waveletJNI = new WaveletJNI();

      waveletJNI.waveletConvert(
          audioFTPower,
          audioSamples,
          pitchFreqSet,
          dt,
          (double) pFactor,
          (double) tFactor,
          sampleIndexSize,
          sampleLength,
          pitchRange,
          progressListener);
    }

    return true;
  }
Exemple #6
0
    private void populate() {
      // set up for a new population
      Vector oldPop = this.positions;
      this.positions = new Vector(50, 50);

      // first browse the old population and make changes
      for (int i = 0; i < oldPop.size(); i++) {
        Position a = (Position) oldPop.get(i);
        if (a.symPosNo < this.symPos.length) {
          Point3d sPos = this.symPos[a.symPosNo];
          if (sPos != null) {
            Point3d newPos = new Point3d(sPos);
            newPos.add(a.expandTranslation);
            if (this.isPosInBounds(newPos)
                && Model3d.this.getAtomHere(this.positions, newPos) == null) {
              a.changePos(newPos);
              this.positions.add(a);
              // System.out.println("move "+a);
              continue;
            }
          }
        }
        // invalid, duplicate or out of bounds, remove
        // System.out.println("del "+a);
        a.del();
      }

      // now add potentially new appeared atoms
      for (double i = -Math.ceil(Model3d.this.exm - 1);
          i <= Math.floor(Model3d.this.exp + 1) + 1;
          i++)
        for (double j = -Math.ceil(Model3d.this.eym - 1);
            j <= Math.floor(Model3d.this.eyp + 1) + 1;
            j++)
          for (double k = -Math.ceil(Model3d.this.ezm - 1);
              k <= Math.floor(Model3d.this.ezp + 1) + 1;
              k++) {
            Vector3d v = new Vector3d(i, j, k);
            for (int l = 0; l < this.symPos.length; l++) {
              if (this.symPos[l] == null) continue;
              Point3d p = new Point3d(this.symPos[l]);
              p.add(v);
              // TODO
              if (this.isPosInBounds(p) && Model3d.this.getAtomHere(this.positions, p) == null) {
                // if (isPosInBounds(round(p)) &&
                // getAtomHere(positions, p)==null) {
                Position a =
                    new Position(this.root, this, p, v, this.radius, this.color, l, !this.hidden);
                this.positions.add(a);
                // if (!isPosInBounds(p))System.out.println("xx
                // "+p);
              }
            }
          }
    }
Exemple #7
0
 public void blockgen() {
   Component temporaryLostComponent = null;
   pos[0] = 0;
   pos[1] = 1;
   rand = (int) (Math.floor(Math.random() * 7 + 1));
   centralx = 4;
   centraly = 0;
   System.out.print(rand);
   if ((b[4 + prof[pos[0]][0][rand - 1].x][prof[pos[0]][0][rand - 1].y].getBackground()
           == Color.DARK_GRAY)
       && (b[4 + prof[pos[0]][1][rand - 1].x][prof[pos[0]][1][rand - 1].y].getBackground()
           == Color.DARK_GRAY)
       && (b[4 + prof[pos[0]][2][rand - 1].x][prof[pos[0]][2][rand - 1].y].getBackground()
           == Color.DARK_GRAY)
       && (b[4 + prof[pos[0]][3][rand - 1].x][prof[pos[0]][3][rand - 1].y].getBackground()
           == Color.DARK_GRAY)) {
     b[4 + prof[pos[0]][0][rand - 1].x][prof[pos[0]][0][rand - 1].y].setBackground(rnd[rand - 1]);
     b[4 + prof[pos[0]][1][rand - 1].x][prof[pos[0]][1][rand - 1].y].setBackground(rnd[rand - 1]);
     b[4 + prof[pos[0]][2][rand - 1].x][prof[pos[0]][2][rand - 1].y].setBackground(rnd[rand - 1]);
     b[4 + prof[pos[0]][3][rand - 1].x][prof[pos[0]][3][rand - 1].y].setBackground(rnd[rand - 1]);
     go();
   } else {
     JOptionPane.showMessageDialog(
         temporaryLostComponent, "Game Over! You cleared " + rowsclrd + " rows, well done!");
     System.exit(0);
   }
 }
Exemple #8
0
 /*
  * Return the number of fractional digits required to display the given
  * number. No number larger than 15 is returned (if more than 15 digits are
  * required, 15 is returned).
  */
 private static int numFracDigits(double num) {
   int numdigits = 0;
   while (numdigits <= 15 && num != Math.floor(num)) {
     num *= 10.0;
     numdigits += 1;
   }
   return numdigits;
 }
Exemple #9
0
 public void updateRoll(int i) {
   _dieRoll = i;
   twoDice =
       new int[] {
         (int) Math.max(Math.floor(Math.random() * Math.min(_dieRoll - 1, 5)) + 1, _dieRoll - 6), 1
       };
   twoDice[1] = _dieRoll - twoDice[0];
   repaint();
 }
Exemple #10
0
 /*
  * Given a number, round up to the nearest power of ten times 1, 2, or 5.
  *
  * Note: The argument must be strictly positive.
  */
 private static double roundUp(double val) {
   int exponent = (int) Math.floor(log10(val));
   val *= Math.pow(10, -exponent);
   if (val > 5.0) val = 10.0;
   else if (val > 2.0) val = 5.0;
   else if (val > 1.0) val = 2.0;
   val *= Math.pow(10, exponent);
   return val;
 }
  public void addCarrier(FireflyCarrier carrier) {
    list.add(carrier);
    add(carrier);

    int columns = (int) Math.floor(Math.sqrt(list.size()));
    gridLayout.setColumns(columns);
    gridLayout.setRows(list.size() / columns);
    updateUI();
  }
Exemple #12
0
  private int[] setUpNearest(MouseEvent e) {

    int mousex = e.getX() - _display_offset[0];
    int mousey = e.getY() - _display_offset[1];

    int i = 0;
    int j;

    j = (int) Math.round((mousey - hextop) * 1.0 / intervalUp);

    if ((j % 2 + (rings - 1) % 2) == 0 || (((j - 1) % 2 + (rings) % 2) == 0)) {
      int glob = 1;
      for (i = 0;
          (Math.floor((i + 1) / 2) * radius + Math.floor(i / 2) * radius * 2)
              < mousex - hexleft - radius / 2;
          i++) glob += (((i % 2) == 0) ? 1 : 3);

      double dx =
          (Math.floor((i + 1) / 2) * radius + Math.floor(i / 2) * radius * 2)
              - (mousex - hexleft - radius / 2);

      if ((i % 2) == 1 && dx > radius / 2) {
        i = i - 1;
        glob -= 1;
      } else if ((i % 2) == 0 && dx > radius) {
        i = i - 1;
        glob -= 3;
      }

      i = glob;

    } else {
      int glob = 0;
      for (i = 0;
          (Math.floor((i + 1) / 2) * radius * 2 + Math.floor(i / 2) * radius) < mousex - hexleft;
          i++) glob += (((i % 2) == 0) ? 3 : 1);

      double dx =
          (Math.floor((i + 1) / 2) * radius * 2 + Math.floor(i / 2) * radius) - (mousex - hexleft);

      if ((i % 2) == 0 && dx > radius / 2) {
        i = i - 1;
        glob -= 1;
      } else if ((i % 2) == 1 && dx > radius) {
        i = i - 1;
        glob -= 3;
      }

      i = glob;
    }

    return new int[] {i, j};
  }
Exemple #13
0
  private boolean buildNoteSequence() {

    noteSequence = new NoteSequence();

    double quantizeBeatFactor = quantizeBeatSetting * 1000.0 * 60.0 / (double) getBPM();
    double quantizeDurationFactor = quantizeDurationSetting * 1000.0 * 60.0 / (double) getBPM();

    for (int i = 0; i < noteList.size(); i++) {
      noteListElement = noteList.get(i);

      if (noteListElement.underTone == true) {
        continue;
      }

      note = noteListElement.note;

      if (note < getLowPitch()) continue;
      if (note > getHighPitch()) continue;

      double startTime = (double) (noteListElement.startTime);

      if (quantizeBeatFactor != 0.0)
        startTime = Math.floor(startTime / quantizeBeatFactor) * quantizeBeatFactor;
      long startTick = 1 + (long) (startTime * getTickRate() / 1000.0);

      double endTime = (double) (noteListElement.endTime);

      if (quantizeBeatFactor != 0.0)
        endTime = Math.ceil(endTime / quantizeBeatFactor) * quantizeBeatFactor;
      if (quantizeDurationFactor != 0)
        endTime =
            startTime
                + (Math.ceil((endTime - startTime) / quantizeDurationFactor)
                    * quantizeDurationFactor);

      long endTick = 1 + (long) (endTime * getTickRate() / 1000.0);

      if ((endTick - startTick) < 1) endTick = startTick + 1;
      System.out.println(
          "times: " + startTime + ", " + endTime + ", " + getStartTime() + ", " + getEndTime());
      if (endTime < getStartTime()) continue;
      if (startTime > getEndTime()) continue;

      velocity = 64;
      noteSequence.add(new NoteSequenceElement(note, ON, startTick, velocity));
      noteSequence.add(new NoteSequenceElement(note, OFF, endTick, velocity));
    }

    if (noteSequence.size() == 0) {
      return false;
    } else {
      noteSequence.sort();
      return true;
    }
  }
  protected ArrayList<SquareZone> createSquaresGrid(
      int UTMZone,
      String hemisphere,
      Sector UTMZoneSector,
      double minEasting,
      double maxEasting,
      double minNorthing,
      double maxNorthing) {
    ArrayList<SquareZone> squares = new ArrayList<SquareZone>();
    double startEasting = Math.floor(minEasting / ONEHT) * ONEHT;
    double startNorthing = Math.floor(minNorthing / ONEHT) * ONEHT;
    int cols = (int) Math.ceil((maxEasting - startEasting) / ONEHT);
    int rows = (int) Math.ceil((maxNorthing - startNorthing) / ONEHT);
    SquareZone[][] squaresArray = new SquareZone[rows][cols];
    int col = 0;
    for (double easting = startEasting; easting < maxEasting; easting += ONEHT) {
      int row = 0;
      for (double northing = startNorthing; northing < maxNorthing; northing += ONEHT) {
        SquareZone sz =
            new SquareZone(UTMZone, hemisphere, UTMZoneSector, easting, northing, ONEHT);
        if (sz.boundingSector != null && !sz.isOutsideGridZone()) {
          squares.add(sz);
          squaresArray[row][col] = sz;
        }
        row++;
      }
      col++;
    }

    // Keep track of neighbors
    for (col = 0; col < cols; col++) {
      for (int row = 0; row < rows; row++) {
        SquareZone sz = squaresArray[row][col];
        if (sz != null) {
          sz.setNorthNeighbor(row + 1 < rows ? squaresArray[row + 1][col] : null);
          sz.setEastNeighbor(col + 1 < cols ? squaresArray[row][col + 1] : null);
        }
      }
    }

    return squares;
  }
Exemple #15
0
 public void makeAvatarOrder() {
   int nRand = (int) Math.floor((Math.random() + 1) + 0.5);
   String sOrder = "A,0|B,0|A,1|B,1|A,2|B,2|A,3|B,3|A,4|B,4";
   String sOrder2 = "B,0|A,0|B,1|A,1|B,2|A,2|B,3|A,3|B,4|A,4";
   if (nRand == 1) {
     makeAvatarOrder(sOrder);
     oConn.send("avatar order", sOrder2);
   } else {
     makeAvatarOrder(sOrder2);
     oConn.send("avatar order", sOrder);
   }
 }
Exemple #16
0
  /**
   * this is the central method of this class. takes axis range parameters and produces a list of
   * string representations of nicely rounded numbers within the given range. these strings are
   * intended for use as axis tic labels. note: to find out where to plot each tic label simply use
   * <br>
   * <code>float ticval = Float.parseFloat(ticstring);</code>
   *
   * @param ticMinVal no tics will be created for less than this value.
   * @param ticMaxVal no tics will be created for greater than this value.
   * @param maxTics returned vector will contain no more labels than this number.
   * @param isLog set to true in case of log10 numbers
   * @return a Vector containing formatted label strings which should also be parsable into floating
   *     point numbers (in order to plot them).
   */
  public static Vector<String> computeTicks(
      double ticMinVal, double ticMaxVal, int maxTicks, boolean isLog) {
    // double xStep = roundUp((ticMaxVal-ticMinVal)/maxTicks);

    double xStep = calculateTicSep(ticMinVal, ticMaxVal, maxTicks);

    int numfracdigits = numFracDigits(xStep);

    // Compute x starting point so it is a multiple of xStep.
    double xStart = xStep * Math.ceil(ticMinVal / xStep);
    Vector xgrid = null;
    Vector<String> labels = new Vector<String>();
    // Label the axis. The labels are quantized so that
    // they don't have excess resolution.

    if (!isLog) {
      for (double xpos = xStart; xpos <= ticMaxVal; xpos += xStep) {
        String snum = formatNum(xpos, numfracdigits);
        labels.addElement(snum);
      }
      // log scale: special case
    } else {

      int t1 = 0;
      int t2 = 0;
      if (ticMinVal > 0) t1 = (int) Math.floor(log10(ticMinVal) - 0.5);
      if (ticMinVal < 0) t1 = -1 * (int) Math.floor(log10(-1 * ticMinVal) - 0.5);
      if (ticMaxVal > 0) t2 = (int) Math.floor(log10(ticMaxVal) + 1.0);
      if (ticMaxVal < 0) t2 = -1 * (int) Math.floor(log10(-1 * ticMaxVal) + 1.0);

      // System.out.println("min = " + xmin + ", max = " + xmax);
      for (int i = t1; i < t2 + 1; i++) {
        double pp = Math.pow(10.0, i);
        // System.out.println(pp);
        labels.addElement(Double.toString(pp));
      }
    }

    return labels;
  }
Exemple #17
0
  public void accumulateBilinear(double x, double y, double s)
        /* Bilinearly accumulates 's' to the four integer grid points surrounding
         *   the continuous coordinate (x, y). */
      {
    double xpf = Math.floor(x);
    int xi = (int) xpf;
    double xf = x - xpf;

    double ypf = Math.floor(y);
    int yi = (int) ypf;
    double yf = y - ypf;

    double b;
    b = (1.0 - xf) * (1.0 - yf);
    accumulate(xi, yi, s * b);
    b = xf * (1.0 - yf);
    accumulate(xi + 1, yi, s * b);
    b = (1.0 - xf) * yf;
    accumulate(xi, yi + 1, s * b);
    b = xf * yf;
    accumulate(xi + 1, yi + 1, s * b);
  }
Exemple #18
0
 public void printDebug() {
   Iterator<StringBuilder> it = rows.iterator();
   int i = 0;
   System.out.println(
       "    " + StringUtils.repeatString("0123456789", (int) Math.floor(getWidth() / 10) + 1));
   while (it.hasNext()) {
     String row = it.next().toString();
     String index = Integer.toString(i);
     if (i < 10) index = " " + index;
     System.out.println(index + " (" + row + ")");
     i++;
   }
 }
  public Color getColorAt(double x, double y) {
    int col = img.getRGB((int) x, (int) y);
    double r = col >> 16 & 0xff;
    double g = col >> 8 & 0xff;
    double b = col & 0xff;

    int col_r = img.getRGB((int) x + 1, (int) y);
    double rr = col_r >> 16 & 0xff;
    double gr = col_r >> 8 & 0xff;
    double br = col_r & 0xff;

    double fact = x - Math.floor(x);

    double rf = r + (rr - r) * fact;
    double gf = g + (gr - g) * fact;
    double bf = b + (br - b) * fact;

    col = img.getRGB((int) x, (int) y + 1);
    r = col >> 16 & 0xff;
    g = col >> 8 & 0xff;
    b = col & 0xff;

    col_r = img.getRGB((int) x + 1, (int) y + 1);
    rr = col_r >> 16 & 0xff;
    gr = col_r >> 8 & 0xff;
    br = col_r & 0xff;

    double rf2 = r + (rr - r) * fact;
    double gf2 = g + (gr - g) * fact;
    double bf2 = b + (br - b) * fact;

    fact = y - Math.floor(y);

    double rff = rf + (rf2 - rf) * fact;
    double gff = gf + (gf2 - gf) * fact;
    double bff = bf + (bf2 - bf) * fact;

    return new Color((int) rff, (int) gff, (int) bff);
  }
Exemple #20
0
  public double getBilinear(double x, double y)
        /* Returns: the bilinearly-interpolated value of the continuous field
         *   at (x, y).
         * Requires: (x, y) is inside the domain of the field */
      {
    if (!inBounds(x, y))
      throw new RuntimeException(
          "ScalarImage.getBilinear: RuntimeException at (" + x + "," + y + ")");

    int xi, yi;
    double xf, yf;
    if (x == (double) (width - 1)) {
      xi = width - 2;
      xf = 1.0;
    } else {
      double xpf = Math.floor(x);
      xi = (int) xpf;
      xf = x - xpf;
    }
    if (y == (double) (height - 1)) {
      yi = height - 2;
      yf = 1.0;
    } else {
      double ypf = Math.floor(y);
      yi = (int) ypf;
      yf = y - ypf;
    }

    double b1 = get(xi, yi);
    double b2 = get(xi + 1, yi);
    double b3 = get(xi, yi + 1);
    double b4 = get(xi + 1, yi + 1);

    double bb1 = b1 + xf * (b2 - b1);
    double bb2 = b3 + xf * (b4 - b3);

    return bb1 + yf * (bb2 - bb1);
  }
  public void XRCompositeTraps(int dst, int srcX, int srcY, TrapezoidList trapList) {
    int renderReferenceX = 0;
    int renderReferenceY = 0;

    if (trapList.getP1YLeft(0) < trapList.getP2YLeft(0)) {
      renderReferenceX = trapList.getP1XLeft(0);
      renderReferenceY = trapList.getP1YLeft(0);
    } else {
      renderReferenceX = trapList.getP2XLeft(0);
      renderReferenceY = trapList.getP2YLeft(0);
    }

    renderReferenceX = (int) Math.floor(XRUtils.XFixedToDouble(renderReferenceX));
    renderReferenceY = (int) Math.floor(XRUtils.XFixedToDouble(renderReferenceY));

    con.renderCompositeTrapezoids(
        compRule,
        src.picture,
        XRUtils.PictStandardA8,
        dst,
        renderReferenceX,
        renderReferenceY,
        trapList);
  }
Exemple #22
0
  public boolean load(File file) {

    this.file = file;

    if (file != null && file.isFile()) {
      try {
        errStr = null;
        audioInputStream = AudioSystem.getAudioInputStream(file);

        fileName = file.getName();

        format = audioInputStream.getFormat();

      } catch (Exception ex) {
        reportStatus(ex.toString());
        return false;
      }
    } else {
      reportStatus("Audio file required.");
      return false;
    }

    numChannels = format.getChannels();
    sampleRate = (double) format.getSampleRate();
    sampleBitSize = format.getSampleSizeInBits();
    long frameLength = audioInputStream.getFrameLength();
    long milliseconds = (long) ((frameLength * 1000) / audioInputStream.getFormat().getFrameRate());
    double audioFileDuration = milliseconds / 1000.0;

    if (audioFileDuration > MAX_AUDIO_DURATION) duration = MAX_AUDIO_DURATION;
    else duration = audioFileDuration;

    frameLength = (int) Math.floor((duration / audioFileDuration) * (double) frameLength);

    try {
      audioBytes = new byte[(int) frameLength * format.getFrameSize()];
      audioInputStream.read(audioBytes);
    } catch (Exception ex) {
      reportStatus(ex.toString());
      return false;
    }

    getAudioData();

    return true;
  }
Exemple #23
0
 public String getDebugString() {
   StringBuilder buffer = new StringBuilder();
   Iterator<StringBuilder> it = rows.iterator();
   int i = 0;
   buffer
       .append("    ")
       .append(StringUtils.repeatString("0123456789", (int) Math.floor(getWidth() / 10) + 1))
       .append("\n");
   while (it.hasNext()) {
     String row = it.next().toString();
     String index = Integer.toString(i);
     if (i < 10) index = " " + index;
     row = row.replaceAll("\n", "\\\\n");
     row = row.replaceAll("\r", "\\\\r");
     buffer.append(index).append(" (").append(row).append(")\n");
     i++;
   }
   return buffer.toString();
 }
Exemple #24
0
  /**
   * Draws a single arrow head
   *
   * @param aG the canvas to draw on;
   * @param aXpos the X position of the arrow head;
   * @param aYpos the (center) Y position of the arrow head;
   * @param aFactor +1 to have a left-facing arrow head, -1 to have a right-facing arrow head;
   * @param aArrowWidth the total width of the arrow head;
   * @param aArrowHeight the total height of the arrow head.
   */
  public static final void drawArrowHead(
      final Graphics2D aG,
      final int aXpos,
      final int aYpos,
      final int aFactor,
      final int aArrowWidth,
      final int aArrowHeight) {
    final double halfHeight = aArrowHeight / 2.0;
    final int x1 = aXpos + (aFactor * aArrowWidth);
    final int y1 = (int) Math.ceil(aYpos - halfHeight);
    final int y2 = (int) Math.floor(aYpos + halfHeight);

    final Polygon arrowHead = new Polygon();
    arrowHead.addPoint(aXpos, aYpos);
    arrowHead.addPoint(x1, y1);
    arrowHead.addPoint(x1, y2);

    aG.fill(arrowHead);
  }
Exemple #25
0
  /**
   * Calculation of the separation length between tics. Some smart rounding algorithms are needed to
   * get the scaling properly in case of data going to 10.3 or so... Useful stuff stolen from the
   * Gnuplot sources, thank you guys!!
   */
  public static double calculateTicSep(double min, double max, int maxNumberOfTicks) {
    double xnorm, tic, posns;
    double lrange = log10(Math.abs(min - max));
    double fl = Math.floor(lrange);
    xnorm = Math.pow(10.0, lrange - fl);
    posns = maxNumberOfTicks / xnorm;

    if (posns > 40) tic = 0.05; // eg 0, .05, .10, ...
    else if (posns > 20) tic = 0.1; // eg 0, .1, .2, ...
    else if (posns > 10) tic = 0.2; // eg 0,0.2,0.4,...
    else if (posns > 4) tic = 0.5; // 0,0.5,1,
    else if (posns > 1) tic = 1; // 0,1,2,....
    else if (posns > 0.5) tic = 2; // 0, 2, 4, 6
    else if (posns > 0.2) tic = 10; // 0, 10, 100, 6
    else tic = Math.ceil(xnorm);

    tic *= Math.pow(10.0, fl);

    return tic;
  }
  public void move() {
    // change direction?
    if (Math.random() * 100 < directionChangeProbability) // Math.random gives 0 to .9999
    bugDirection = (int) Math.floor(Math.random() * NUMBER_OF_DIRECTIONS);

    if (bugDirection == LEFT) xPosition -= horizontalMovement;
    else if (bugDirection == RIGHT) xPosition += horizontalMovement;
    else if (bugDirection == UP) yPosition -= verticalMovement;
    else if (bugDirection == DOWN) yPosition += verticalMovement;

    drawBug();

    // hit edge of window and need to turn around?
    if (bugDirection == UP && atTopEdge()) {
      bugDirection = DOWN;
    } else if (bugDirection == DOWN && atBottomEdge()) {
      bugDirection = UP;
    } else if (bugDirection == LEFT && atLeftEdge()) {
      bugDirection = RIGHT;
    } else if (bugDirection == RIGHT && atRightEdge()) {
      bugDirection = LEFT;
    }
  }
 void selectBlock() {
   try {
     System.out.println("Enter the value of n, k, L and W  : ");
     sc = new Scanner(System.in);
     n = sc.nextInt();
     k = sc.nextInt();
     L = sc.nextInt();
     W = sc.nextInt();
     B = new int[L][W];
     for (int i = 0; i <= L - 1; i++) {
       for (int j = 0; j <= W - 1; j++) {
         B[i][j] = pixels[(n + i) % height][(k + j) % width];
       }
     }
     S = (int) Math.floor(Math.log(L * W) / Math.log(2));
     key = new int[S];
     BufferedImage im = new BufferedImage(W, L, BufferedImage.TYPE_3BYTE_BGR);
     for (int i = 0; i <= L - 1; i++) for (int j = 0; j <= W - 1; j++) im.setRGB(j, i, B[i][j]);
     File file = new File("block.png");
     ImageIO.write(im, "png", file);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  public void paintProbe(Graphics2D g2, int x1, int y1, int x2, int y2, double tmin, double tmax) {
    g2.setStroke(stroke);
    g2.setColor(color);

    int ppx = -1, ppy = -1;
    for (int i = 0; i < values.size(); i++) {
      Double v = values.get(i);
      if (v != null && tmax - tmin > 0.0) {
        double frac = (v - tmin) / (tmax - tmin);
        int pixY = y2 - (int) Math.round(frac * (y2 - y1));
        int pixX = x1 + (int) Math.floor((double) (i + 1) / (double) (values.size() + 2));

        if (ppx != -1) {
          g2.drawLine(ppx, ppy, pixX, pixY);
        }

        ppx = pixX;
        ppy = pixY;

      } else {
        ppx = ppy = -1;
      }
    }
  }
 private final int YtoTileY(int y) {
   return (int) Math.floor((double) (y - tileGridYOffset) / tileHeight);
 }
 private final int XtoTileX(int x) {
   return (int) Math.floor((double) (x - tileGridXOffset) / tileWidth);
 }