Example #1
0
  /** make new shape polygon */
  private void reMakePolygonShape() {
    ConvexHull convexHull;

    List<Point> newPoints = new ArrayList<Point>();

    for (int j = 0; j < polygon.npoints; j++) {

      if (mainClusterShape.contains(polygon.xpoints[j], polygon.ypoints[j])) {
        newPoints.add(new Point(polygon.xpoints[j], polygon.ypoints[j]));
      }
    }

    for (Point2D point2D : getIntersectPoint()) {
      newPoints.add(new Point((int) point2D.getX(), (int) point2D.getY()));
    }

    for (int i = 0; i < mainClusterShape.npoints; i++) {
      if (polygon.contains(mainClusterShape.xpoints[i], mainClusterShape.ypoints[i])) {
        Point point = new Point(mainClusterShape.xpoints[i], mainClusterShape.ypoints[i]);
        newPoints.add(point);
      }
    }

    convexHull = new ConvexHull();

    for (Point point : newPoints) {
      convexHull.addPoint((int) point.getX(), (int) point.getY());
    }

    setPolygon(convexHull.convex());
    newPoints.clear();
  }
Example #2
0
  /**
   * make new shape polygon
   *
   * @param p
   * @param polygon
   * @param intersectPoint
   */
  private Polygon reMakePolygonShape(Polygon p, Polygon polygon, List<Point2D> intersectPoint) {
    ConvexHull convexHull;

    List<Point> newPoints = new ArrayList<Point>();

    for (int j = 0; j < p.npoints; j++) {
      if (polygon.contains(p.xpoints[j], p.ypoints[j])) {
        newPoints.add(new Point(p.xpoints[j], p.ypoints[j]));
      }
    }

    for (Point2D point2D : intersectPoint) {
      newPoints.add(new Point((int) point2D.getX(), (int) point2D.getY()));
    }

    for (int i = 0; i < polygon.npoints; i++) {
      if (p.contains(polygon.xpoints[i], polygon.ypoints[i])) {
        Point point = new Point(polygon.xpoints[i], polygon.ypoints[i]);
        newPoints.add(point);
      }
    }

    convexHull = new ConvexHull();

    for (Point point : newPoints) {
      convexHull.addPoint((int) point.getX(), (int) point.getY());
    }

    Polygon polygon1 = convexHull.convex();
    //        newPoints.clear();

    return polygon1;
  }
Example #3
0
  /**
   * Return a list of all objects in the selection, respecting the different modifier.
   *
   * @param alt Whether the alt key was pressed, which means select all objects that are touched,
   *     instead those which are completely covered.
   * @return The collection of selected objects.
   */
  public Collection<OsmPrimitive> getSelectedObjects(boolean alt) {

    Collection<OsmPrimitive> selection = new LinkedList<>();

    // whether user only clicked, not dragged.
    boolean clicked = false;
    Rectangle bounding = lasso.getBounds();
    if (bounding.height <= 2 && bounding.width <= 2) {
      clicked = true;
    }

    if (clicked) {
      Point center = new Point(lasso.xpoints[0], lasso.ypoints[0]);
      OsmPrimitive osm = nc.getNearestNodeOrWay(center, OsmPrimitive.isSelectablePredicate, false);
      if (osm != null) {
        selection.add(osm);
      }
    } else {
      // nodes
      for (Node n : nc.getCurrentDataSet().getNodes()) {
        if (n.isSelectable() && lasso.contains(nc.getPoint2D(n))) {
          selection.add(n);
        }
      }

      // ways
      for (Way w : nc.getCurrentDataSet().getWays()) {
        if (!w.isSelectable() || w.getNodesCount() == 0) {
          continue;
        }
        if (alt) {
          for (Node n : w.getNodes()) {
            if (!n.isIncomplete() && lasso.contains(nc.getPoint2D(n))) {
              selection.add(w);
              break;
            }
          }
        } else {
          boolean allIn = true;
          for (Node n : w.getNodes()) {
            if (!n.isIncomplete() && !lasso.contains(nc.getPoint(n))) {
              allIn = false;
              break;
            }
          }
          if (allIn) {
            selection.add(w);
          }
        }
      }
    }
    return selection;
  }
Example #4
0
  private static void graph(Polygon[] finalPolygons) {
    int weiners = 0;
    String[] Starter = sPoint.split(",");
    String[] Ender = ePoint.split(",");
    int endx = Integer.parseInt(Ender[0]);
    int endy = Integer.parseInt(Ender[1]);
    int G = 40;
    for (int i = 0; i < G; i++) {
      for (int j = 0; j < G; j++) {
        int loketest = 0;
        if ((i == Startx && j == Starty) || i == endx && j == endy) {
          loketest = 2;
        }
        for (Polygon helpme : finalPolygons) {
          if (helpme.contains(i, j)) {
            loketest = 1;
          }
        }
        if (loketest == 1) {
          System.out.print("1");
        } else if (loketest == 2) {
          System.out.print("X");
        } else {
          System.out.print("0");
        }
      }

      System.out.println("     \t");
      weiners++;
    }
  }
Example #5
0
  /**
   * This method exists for the following reason:
   *
   * <p>The segmenter receives at each frame a cropped image to operate on, depending on the user
   * specifying a ROI. It therefore returns spots whose coordinates are with respect to the top-left
   * corner of the ROI, not of the original image.
   *
   * <p>This method modifies the given spots to put them back in the image coordinate system.
   * Additionally, is a non-square ROI was specified (e.g. a polygon), it prunes the spots that are
   * not within the polygon of the ROI.
   *
   * @param spotsThisFrame the spot list to inspect
   * @param settings the {@link Settings} object that will be used to retrieve the image ROI and
   *     cropping information
   * @return a list of spot. Depending on the presence of a polygon ROI, it might be a new, pruned
   *     list. Or not.
   */
  protected List<Spot> translateAndPruneSpots(
      final List<Spot> spotsThisFrame, final Settings settings) {
    // Get Roi
    final Polygon polygon;
    if (null == settings.imp || null == settings.imp.getRoi()) {
      polygon = null;
    } else {
      polygon = settings.imp.getRoi().getPolygon();
    }

    // Put them back in the right referential
    final float[] calibration = settings.getCalibration();
    TMUtils.translateSpots(
        spotsThisFrame,
        settings.xstart * calibration[0],
        settings.ystart * calibration[1],
        settings.zstart * calibration[2]);
    List<Spot> prunedSpots;
    // Prune if outside of ROI
    if (null != polygon) {
      prunedSpots = new ArrayList<Spot>();
      for (Spot spot : spotsThisFrame) {
        if (polygon.contains(
            spot.getFeature(Spot.POSITION_X) / calibration[0],
            spot.getFeature(Spot.POSITION_Y) / calibration[1])) prunedSpots.add(spot);
      }
    } else {
      prunedSpots = spotsThisFrame;
    }
    return prunedSpots;
  }
Example #6
0
 private int countAttackableElixirs(
     final List<RegionMatch> doFindAll, final List<Rectangle> matchedElixirs, final Path next) {
   int attackableElixirs = 0;
   int c = 0;
   RECT_LOOP:
   for (final RegionMatch i : doFindAll) {
     // if matched area is out of enemy poly
     if (!ENEMY_BASE_POLY.contains(i.x, i.y)) {
       continue;
     }
     // check if it's an existing match
     for (final Rectangle r : matchedElixirs) {
       if (r.intersects(i.getBounds())) {
         break RECT_LOOP;
       }
     }
     c++;
     matchedElixirs.add(i.getBounds());
     if (next.getFileName().toString().startsWith("empty")) {
       attackableElixirs--;
     } else if (next.getFileName().toString().startsWith("full")) {
       attackableElixirs++;
     }
     logger.finest("\t" + i.getBounds() + " score: " + i.getScore());
   }
   if (c > 0) {
     logger.finest(
         String.format("\tfound %d elixirs matching %s\n", c, next.getFileName().toString()));
   }
   return attackableElixirs;
 }
Example #7
0
 @Override
 public boolean isInBounds(Bounds bounds) {
   // TODO there is no float polygon, so I have to think about s.th. else (or leave it the way it
   // is now)
   int x[] = new int[nodes.length];
   int y[] = new int[nodes.length];
   int i = 0;
   for (Node node : nodes) {
     x[i] = (int) (node.getPos().getLongitude() * 1000); // 1000 is a random factor, can be changed
     i++;
   }
   i = 0;
   for (Node node : nodes) {
     y[i] = (int) (node.getPos().getLatitude() * 1000);
     i++;
   }
   Polygon area = new Polygon(x, y, nodes.length);
   Rectangle2D.Double box =
       new Rectangle2D.Double(
           bounds.getLeft() * 1000 - 1,
           bounds.getTop() * 1000 - 1,
           bounds.getWidth() * 1000 + 1,
           bounds.getHeight() * 1000 + 1);
   boolean inside = false;
   for (Node node : nodes) {
     if (node.isInBounds(bounds)) {
       inside = true;
     }
   }
   return inside || area.contains(box) || area.intersects(box);
 }
Example #8
0
  /**
   * this method calculates the border entities, using entities and convexHull of the entities
   *
   * @param convex is the convex of all Entities
   * @param entities are the self entities
   * @param scale is the scale for making smaller convex hull
   */
  public Set<EntityID> getBorderEntities(ConvexHull convex, Set<EntityID> entities, double scale) {
    if (scale >= 1.0) {
      System.err.println(
          "scale should not be over 1.0! check it in border entities, border entities doesn't work now!");
      return null;
    }

    Building building;
    Polygon convexObject = convex.convex();
    Set<EntityID> borderEntities = new FastSet<EntityID>();

    if (convexObject.npoints
        == 0) { // I don't know why this happens, report me if this error writes usually! TODO check
      // this if something comes wrong here
      System.out.println("Something gone wrong in setting border entities for Firebrigade!!!");
      return null;
    }

    Polygon smallBorderPolygon = scalePolygon(convexObject, scale);
    //        Polygon bigBorderPolygon = scalePolygon(convexObject, 1.1);

    if (MRLConstants.LAUNCH_VIEWER) {
      //            MrlConvexHullLayer.BIG_Whole_BORDER_HULL = convex;
      //            MrlConvexHullLayer.SMALL_Whole_BORDER_HULL = smallBorderPolygon;
    }

    for (EntityID entityID : entities) {

      StandardEntity entity = world.getEntity(entityID);

      if (entity instanceof Refuge) continue;
      if (!(entity instanceof Building)) continue;
      building = (Building) entity;
      int vertexes[] = building.getApexList();
      for (int i = 0; i < vertexes.length; i += 2) {

        if ((convexObject.contains(vertexes[i], vertexes[i + 1]))
            && !(smallBorderPolygon.contains(vertexes[i], vertexes[i + 1]))) {
          borderEntities.add(building.getID());
          break;
        }
      }
    }

    return borderEntities;
  }
Example #9
0
 /** * find the cluster buildings */
 private void clusterBuildings() {
   for (StandardEntity entity : world.getBuildings()) {
     if (entity instanceof Building) {
       if (polygon.contains(((Building) entity).getX(), ((Building) entity).getY())) {
         this.buildings.add((Building) entity);
       }
     }
   }
 }
Example #10
0
 /** find the cluster roads */
 private void clusterRoad() {
   for (StandardEntity entity : world.getRoads()) {
     if (entity instanceof Road) {
       if (polygon.contains(((Road) entity).getX(), ((Road) entity).getY())) {
         this.roads.add((Road) entity);
       }
     }
   }
 }
Example #11
0
  public boolean isZaznaczono(int x, int y) {
    boolean result = obszar.contains(x, y);

    for (PunktMapy punkt : this.punkty) {
      result |= Metody2D.sasiedztwoPunktu(punkt, x, y);
    }

    return result;
  }
Example #12
0
 /**
  * Checks if any target is inside of the building.
  *
  * @param targets Targets to check.
  */
 public void checkTargetsInside(ArrayList<LinkedList<Node>> targets) {
   // Check which targets that are inside of this building
   for (LinkedList<Node> list : targets) {
     for (Node node : list) {
       if (p.contains(node.getXPos(), node.getYPos())) {
         addInsideTarget(node);
       }
     }
   }
 }
Example #13
0
  public void mouseClicked(MouseEvent e) {

    /* Check for the Polygon region and add ornaments*/
    if (p2.contains(e.getPoint())) {
      count++;
      repaint();
      /*Create and add Ornament*/
      Ornament O = new Ornament(e.getPoint().x, e.getPoint().y, OrnClr);
      Ornlist.add(O);
    }
  }
Example #14
0
 /**
  * Traces the boundary of the area with pixel values within 'tolerance' of the value of the pixel
  * at the starting location. 'tolerance' is in uncalibrated units. 'mode' can be FOUR_CONNECTED or
  * EIGHT_CONNECTED. Mode LEGACY_MODE is for compatibility with previous versions of ImageJ;
  * ignored if tolerance > 0. Mode bit THRESHOLDED_MODE for internal use only; it is set by
  * autoOutline with 'upper' and 'lower' arguments. When successful, npoints>0 and the boundary
  * points can be accessed in the public xpoints and ypoints fields.
  */
 public void autoOutline(int startX, int startY, double tolerance, int mode) {
   if (startX < 0 || startX >= width || startY < 0 || startY >= height) return;
   if (fpixels != null && Float.isNaN(getPixel(startX, startY))) return;
   exactPixelValue = tolerance == 0;
   boolean thresholdMode = (mode & THRESHOLDED_MODE) != 0;
   boolean legacyMode = (mode & LEGACY_MODE) != 0 && tolerance == 0;
   if (!thresholdMode) {
     double startValue = getPixel(startX, startY);
     lowerThreshold = (float) (startValue - tolerance);
     upperThreshold = (float) (startValue + tolerance);
   }
   int x = startX;
   int y = startY;
   int seedX; // the first inside pixel
   if (inside(x, y)) { // find a border when coming from inside
     seedX = x; // (seedX, startY) is an inside pixel
     do {
       x++;
     } while (inside(x, y));
   } else { // find a border when coming from outside (thresholded only)
     do {
       x++;
       if (x >= width) return; // no border found
     } while (!inside(x, y));
     seedX = x;
   }
   boolean fourConnected;
   if (legacyMode) fourConnected = !thresholdMode && !(isLine(x, y));
   else fourConnected = (mode & FOUR_CONNECTED) != 0;
   // now, we have a border between (x-1, y) and (x,y)
   boolean first = true;
   while (true) { // loop until we have not traced an inner hole
     boolean insideSelected = traceEdge(x, y, fourConnected);
     if (legacyMode) return; // in legacy mode, don't care what we have got
     if (insideSelected) { // not an inner hole
       if (first) return; // started at seed, so we got it (sucessful)
       if (xmin <= seedX) { // possibly the correct particle
         Polygon poly = new Polygon(xpoints, ypoints, npoints);
         if (poly.contains(seedX, startY)) return; // successful, particle contains seed
       }
     }
     first = false;
     // we have traced an inner hole or the wrong particle
     if (!inside(x, y))
       do {
         x++; // traverse the hole
         if (x > width) throw new RuntimeException("Wand Malfunction"); // should never happen
       } while (!inside(x, y));
     do {
       x++;
     } while (inside(x, y)); // retry here; maybe no inner hole any more
   }
 }
Example #15
0
 public boolean contains(int x, int y) {
   if (!super.contains(x, y)) return false;
   if (xSpline != null) {
     FloatPolygon poly = new FloatPolygon(xSpline, ySpline, splinePoints);
     return poly.contains(x - this.x, y - this.y);
   } else if (xpf != null) {
     FloatPolygon poly = new FloatPolygon(xpf, ypf, nPoints);
     return poly.contains(x - this.x, y - this.y);
   } else {
     Polygon poly = new Polygon(xp, yp, nPoints);
     return poly.contains(x - this.x, y - this.y);
   }
 }
Example #16
0
  /** find the cluster paths */
  private void clusterPaths() {
    List<Road> roadList = new ArrayList<Road>();
    for (StandardEntity entity : world.getRoads()) {
      if (entity instanceof Road) {
        if (polygon.contains(((Road) entity).getX(), ((Road) entity).getY())) {
          roadList.add((Road) entity);
        }
      }
    }

    for (Road r : roadList) {
      paths.add(world.getPath(r.getID()).getId());
    }
  }
Example #17
0
 /**
  * Creates a target node at the center of this building and mark it as a place of education.
  *
  * @param collisionMatrix The collisionMatrix to check against
  * @param middleX Center x value of polygon bounds
  * @param middleY Center y value of polygon bounds
  */
 private void createEducationCenter(int[][] collisionMatrix, int middleX, int middleY) {
   Node educationCenter;
   // Check that middle (y) is inside of map bounds
   if (Math.round(OSM_Reader.scaleCollision * middleY) >= 0
       && Math.round(OSM_Reader.scaleCollision * middleY) < collisionMatrix.length) {
     for (int x = 0; x <= middleX; x++) {
       // Are we inside of map bounds (x)
       if (Math.round(OSM_Reader.scaleCollision * middleX + x) >= 0
           && Math.round(OSM_Reader.scaleCollision * middleX + x) < collisionMatrix.length) {
         // Is this point inside of the building? (and has no previous cost value)
         if (p.contains(middleX + x, middleY)
             && collisionMatrix[Math.round(OSM_Reader.scaleCollision * middleX + x)][
                     Math.round(OSM_Reader.scaleCollision * middleY)]
                 == 0) {
           educationCenter = new Node(middleX + x, middleY);
           educationCenter.setTag(OSM_Reader.EDUCATION);
           OSM_Reader.targets.get(OSM_Reader.TargetEnums.STUDY.ordinal()).add(educationCenter);
           break;
         }
       }
       // Are we inside of bounds (x)
       if (Math.round(OSM_Reader.scaleCollision * middleX - x) >= 0
           && Math.round(OSM_Reader.scaleCollision * middleX - x) < collisionMatrix.length) {
         // Is this point inside of the building? (and has no previous cost value)
         if (p.contains(middleX - x, middleY)
             && collisionMatrix[Math.round(OSM_Reader.scaleCollision * middleX - x)][
                     Math.round(OSM_Reader.scaleCollision * middleY)]
                 == 0) {
           educationCenter = new Node(middleX - x, middleY);
           educationCenter.setTag(OSM_Reader.EDUCATION);
           OSM_Reader.targets.get(OSM_Reader.TargetEnums.STUDY.ordinal()).add(educationCenter);
           break;
         }
       }
     }
   }
 }
Example #18
0
 /** Verifica se il punto 'pnt' ? sufficientemente vicino alla zona "attiva" del loop. */
 public boolean isSelezionato(Point pnt) {
   final int delta = 5;
   int[] ascisse = new int[4];
   int[] ordinate = new int[4];
   Polygon poly;
   boolean risultato;
   if (rotazione) {
     ascisse[0] = Math.round((float) (xstart - semiw / 2));
     ascisse[1] = Math.round((float) (xstart - semiw / 2));
     ascisse[3] = Math.round((float) (xstart - 3 * semiw / 2));
     ascisse[2] = Math.round((float) (xstart - 3 * semiw / 2));
     ordinate[0] =
         Math.round(
             (float) (ystart + semih + (posCollegamento + 1) * DEFAULT_LINK_DISTANCE - delta));
     ordinate[1] =
         Math.round(
             (float) (ystart + semih + (posCollegamento + 1) * DEFAULT_LINK_DISTANCE + delta));
     ordinate[3] =
         Math.round(
             (float) (ystart + semih + (posCollegamento + 1) * DEFAULT_LINK_DISTANCE - delta));
     ordinate[2] =
         Math.round(
             (float) (ystart + semih + (posCollegamento + 1) * DEFAULT_LINK_DISTANCE + delta));
   } else {
     ascisse[0] = Math.round((float) (xstart + semiw / 2));
     ascisse[1] = Math.round((float) (xstart + semiw / 2));
     ascisse[3] = Math.round((float) (xstart + 3 * semiw / 2));
     ascisse[2] = Math.round((float) (xstart + 3 * semiw / 2));
     ordinate[0] =
         Math.round(
             (float) (ystart - semih - (posCollegamento + 1) * DEFAULT_LINK_DISTANCE - delta));
     ordinate[1] =
         Math.round(
             (float) (ystart - semih - (posCollegamento + 1) * DEFAULT_LINK_DISTANCE + delta));
     ordinate[3] =
         Math.round(
             (float) (ystart - semih - (posCollegamento + 1) * DEFAULT_LINK_DISTANCE - delta));
     ordinate[2] =
         Math.round(
             (float) (ystart - semih - (posCollegamento + 1) * DEFAULT_LINK_DISTANCE + delta));
   }
   poly = new Polygon(ascisse, ordinate, 4);
   risultato = poly.contains(pnt);
   // Nel prototipo ? scritto che le due istruzioni seguenti sono state aggiunte
   // per consentire al 'Garbage Collection' di rimuovere l'oggetto temporaneo 'poly'.
   ascisse = null;
   ordinate = null;
   return risultato;
 }
 /**
  * Método para obtener un tramo a partir de un punto en el panel del mapa.
  *
  * <p>Este método recorre la lista de tramos y busca el tramo que tiene una posicion (x,y) similar
  * a la pasada como parámetro.
  *
  * @param x Posicion a lo largo del eje x (coordenadas del panel)
  * @param y Posicion a lo largo del eje y (coordenadas del panel)
  * @return Tramo encontrado en la posicion dada o null
  */
 public Tramo buscarTramo(int posX, int posY) {
   Iterator<Tramo> iter = modelo.getMapa().getTramos().iterator();
   Tramo sel = null;
   boolean encontrado = false;
   while (!encontrado && iter.hasNext()) {
     Tramo next = iter.next();
     Polygon p = panel_mapa.getRepresentacion().generarAreaTramo(next);
     if (p.contains(posX, posY)) {
       encontrado = true;
       sel = next;
     }
   }
   if (encontrado) return sel;
   else return null;
 }
Example #20
0
 /**
  * java.lang.String findTerritoryName(java.awt.Point)
  *
  * <p>Finds a land territory name or some sea zone name.
  *
  * @param java .awt.point p a point on the map
  */
 private String findTerritoryName(final Point p) {
   String seaName = "there be dragons";
   // try to find a land territory.
   // sea zones often surround a land territory
   for (final String name : m_polygons.keySet()) {
     final Collection<Polygon> polygons = m_polygons.get(name);
     for (final Polygon poly : polygons) {
       if (poly.contains(p)) {
         if (name.endsWith("Sea Zone") || name.startsWith("Sea Zone")) {
           seaName = name;
         } else {
           return name;
         }
       } // if
     } // while
   } // while
   return seaName;
 }
Example #21
0
  /**
   * {@inheritDoc}
   *
   * @return
   */
  @Override
  public K compute(final K in, final K r) {
    final Cursor<BitType> cur = in.localizingCursor();
    ArrayList<Point> points = new ArrayList<Point>();
    while (cur.hasNext()) {
      cur.fwd();
      if (cur.get().get()) {
        points.add(new Point(cur.getIntPosition(m_dimX), cur.getIntPosition(m_dimY)));
      }
    }
    points = quickHull(points);
    final Polygon poly = new Polygon();
    for (final Point p : points) {
      poly.addPoint(p.x, p.y);
    }

    Cursor<BitType> resCur = r.localizingCursor();

    if (m_fill) {
      while (resCur.hasNext()) {
        resCur.fwd();
        if (poly.contains(resCur.getIntPosition(m_dimX), resCur.getIntPosition(m_dimY))) {
          resCur.get().set(true);
        }
      }
    } else {

      // m_imgManFalse.compute(in, r);

      final RandomAccess<BitType> ra = r.randomAccess();

      for (int i = 0; i < poly.npoints - 1; i++) {
        drawLine(ra, poly, i, i + 1, m_dimX, m_dimY);
      }
      if (poly.npoints > 0) {
        drawLine(ra, poly, poly.npoints - 1, 0, m_dimX, m_dimY);
      }
    }
    return r;
  }
Example #22
0
  public void processSectionSpline(boolean shiftDown) {
    mCurrPC.setBatchModeOn();

    if (!shiftDown) mCurrPC.unselectAll();

    // loop on spline pts
    for (int s = 0; s < mSplinePoints.size() - 2; s++) {
      Point p1 = (Point) mSplinePoints.elementAt(s);
      Point p2 = (Point) mSplinePoints.elementAt(s + 1);

      int x1 = p1.x - mLeft - 5;
      int y1 = p1.y - mTop - 5;
      int x2 = p2.x - mLeft - 5;
      int y2 = p2.y - mTop - 5;

      // construct the search polygon
      double dx = x1 - x2;
      double dy = y1 - y2;
      int width1 = ComputeSectionPixelWidth(p1);
      int width2 = ComputeSectionPixelWidth(p2);

      if (dx == 0 && dy == 0) return;
      double dist = (double) Math.pow(dx * dx + dy * dy, 0.5f);

      double p1x = x1 + (double) width1 * (-dy / dist);
      double p1y = y1 + (double) width1 * (dx / dist);

      double p2x = x1 - (double) width1 * (-dy / dist);
      double p2y = y1 - (double) width1 * (dx / dist);

      double p3x = x2 + (double) width2 * (-dy / dist);
      double p3y = y2 + (double) width2 * (dx / dist);

      double p4x = x2 - (double) width2 * (-dy / dist);
      double p4y = y2 - (double) width2 * (dx / dist);

      Polygon srcArea = new Polygon();
      srcArea.addPoint((int) p2x, (int) p2y);
      srcArea.addPoint((int) p1x, (int) p1y);
      srcArea.addPoint((int) p3x, (int) p3y);
      srcArea.addPoint((int) p4x, (int) p4y);

      // search for matches
      byte[] currFilterResults = fdm.getResults();
      double[] yArray1 = getYArray1();
      double[] xArray1 = getXArray1();
      double[] yArray2 = getYArray2();
      double[] xArray2 = getXArray2();
      mCurrPC.setBatchModeOn();
      for (int i = 0; i < mCurrPC.getSize(); i++) {
        if (!mIgnoreFilter
            && (mCurrPC.isDeleted(i) || currFilterResults[i] != 4 || !mCurrPC.isSelectedLayer(i)))
          continue;
        double yi = yArray1[i];
        double xi = xArray1[i];
        double xi2 = Float.NaN;
        double yi2 = Float.NaN;
        double xx2 = Float.NaN;
        double yy2 = Float.NaN;

        // correct the X value if necessary
        xi = correctX(xi);

        double xx1 = (xi - winXOrigin) * winXScale;
        double yy1 = (yi - winYOrigin) * winYScale;

        // correct the Y coordinate if necessary
        yy1 = correctY(yy1);

        if (!isYAxisScaler()) {
          yi2 = yArray2[i];
          yy2 = (yi2 - winYOrigin) * winYScale;
          ;
          yy2 = correctY(yy2);
        } else yy2 = yy1;

        if (!isXAxisScaler()) {
          xi2 = xArray2[i];
          xi2 = correctX(xi2);
          xx2 = (xi2 - winXOrigin) * winXScale;
        } else xx2 = xx1;

        if (srcArea.contains(new Point((int) xx1, (int) yy1))
            || srcArea.contains(new Point((int) xx2, (int) yy2))) {
          mCurrPC.select(i);
        }
      }
    } // for splines

    mSplinePoints.removeAllElements();
    mViewManager.invalidateAllViews();
    mCurrPC.setBatchModeOff();
  }
Example #23
0
  /**
   * Calculates an approximation of the tiles that are making up the building. Sets these tiles
   * values to the corresponding collision values.
   *
   * @param collsionMatrix The collision matrix that is modified
   */
  public void calculateCollision(int[][] collisionMatrix) {
    Rectangle rect = p.getBounds();
    int maxX, maxY, minX, minY;
    maxX = (int) rect.getMaxX();
    maxY = (int) rect.getMaxY();
    minX = (int) rect.getMinX();
    minY = (int) rect.getMinY();

    // If building is a building used for education - find the center of it and add an EDUCATION
    // node
    if (tag.equals(OSM_Reader.EDUCATION)) {
      createEducationCenter(collisionMatrix, (maxX - minX) / 2 + minX, (maxY - minY) / 2 + minY);
    }

    double distance;
    double[] minDistances = new double[targetsInside.size()];
    Arrays.fill(minDistances, Double.MAX_VALUE);
    LinkedList<int[]> closestNodes = new LinkedList<int[]>();
    // Initiate vector with edge points (closest to respective target point)
    for (int i = 0; i < targetsInside.size(); i++) {
      int[] temp = new int[2];
      closestNodes.add(temp);
    }

    // Go through each line of the building
    for (int y = minY; y <= maxY; y++) {
      // Are we inside of map bounds (y)
      if (Math.round(OSM_Reader.scaleCollision * y) >= 0
          && Math.round(OSM_Reader.scaleCollision * y) < collisionMatrix.length) {
        for (int x = minX; x <= maxX; x++) {
          // Are we inside of map bounds (x)
          if (Math.round(OSM_Reader.scaleCollision * x) >= 0
              && Math.round(OSM_Reader.scaleCollision * x) < collisionMatrix.length) {
            // Is this point inside of the building? (and has no previous cost value)
            if (p.contains(x, y)
                && collisionMatrix[Math.round(OSM_Reader.scaleCollision * x)][
                        Math.round(OSM_Reader.scaleCollision * y)]
                    == 0) {
              collisionMatrix[Math.round(OSM_Reader.scaleCollision * x)][
                      Math.round(OSM_Reader.scaleCollision * y)] =
                  cost;

              // On the edge of the building
              if (!p.contains(x - 1, y) || !p.contains(x + 1, y)) {
                Node node;
                // Go through all targets that are inside of the building
                for (int i = 0; i < targetsInside.size(); i++) {
                  node = targetsInside.get(i);

                  // Calculate the Euclidean distance from target to edge
                  distance =
                      Math.sqrt(Math.pow(node.getXPos() - x, 2) + Math.pow(node.getYPos() - y, 2));

                  // Check if target is closer to this edge point
                  if (minDistances[i] > distance) {
                    minDistances[i] = distance;
                    closestNodes.get(i)[0] = x;
                    closestNodes.get(i)[1] = y;
                  }
                }
              }
            }
          }
        }
      }
    }
    createEntranceWays(collisionMatrix, closestNodes);
  }
Example #24
0
  public void rubberbandEnded(Rubberband rb, boolean shiftDown) {
    // get the limits and zoom the plot
    if (mCurrPC == null) return;
    Rectangle rbRect = rb.getBounds();
    if (rbRect.width == 0 || rbRect.height == 0) {
      // click selection
      if (toolMode == Constants.SELECT_MODE) {
        // find any matches at the mouseclick location
        int x = rbRect.x - mLeft - 5;
        int y = rbRect.y - mTop - 5;

        // construct a search region;
        int[] xpoints = {x - 1, x + 1, x + 1, x - 1, x - 1};
        int[] ypoints = {y - 1, y - 1, y + 1, y + 1, y - 1};
        Polygon sr = new Polygon(xpoints, ypoints, 5);

        if (!shiftDown) mCurrPC.unselectAll();

        mCurrPC.setBatchModeOn();

        byte[] currFilterResults = fdm.getResults();
        double[] yArray1 = getYArray1();
        double[] xArray1 = getXArray1();
        double[] yArray2 = getYArray2();
        double[] xArray2 = getXArray2();

        for (int i = 0; i < mCurrPC.getSize(); i++) {
          if (!mIgnoreFilter && (mCurrPC.isDeleted(i) || currFilterResults[i] != 4)
              || !mCurrPC.isSelectedLayer(i)) continue;

          // search for matches
          double yi = yArray1[i];
          double xi = xArray1[i];
          double xi2 = Float.NaN;
          double yi2 = Float.NaN;
          double x2 = Float.NaN;
          double y2 = Float.NaN;

          // correct the X value if necessary
          xi = correctX(xi);

          double x1 = (xi - winXOrigin) * winXScale;
          double y1 = (yi - winYOrigin) * winYScale;

          // correct the Y coordinate if necessary
          y1 = correctY(y1);

          if (!isYAxisScaler()) {
            yi2 = yArray2[i];
            y2 = (yi2 - winYOrigin) * winYScale;
            y2 = correctY(y2);
          } else y2 = y1;

          if (!isXAxisScaler()) {
            xi2 = xArray2[i];
            xi2 = correctX(xi2);
            x2 = (xi2 - winXOrigin) * winXScale;
          } else x2 = x1;

          if (sr.contains(new Point((int) x1, (int) y1))
              || sr.contains(new Point((int) x2, (int) y2))) {
            mCurrPC.select(i);
          }
        }
        mViewManager.invalidateAllViews();
        mCurrPC.setBatchModeOff();
      } else if (toolMode == Constants.ZOOM_MODE) {
        if (!shiftDown) {
          doZoomIn(rbRect);
        } else {
          // zoom out
          double xInc = getXZoomIncrement();
          double yInc = getYZoomIncrement();
          double[] oldYs = {getMaxYVal(), getMinYVal()};
          double[] newYs = {
            getMinYVal() < 0 ? getMinYVal() - yInc : getMinYVal() + yInc,
            getMaxYVal() < 0 ? getMaxYVal() - yInc : getMaxYVal() + yInc
          };
          double[] oldXs = {getMinXVal(), getMaxXVal()};
          double[] newXs = {
            getMinXVal() < 0 ? getMinXVal() - xInc : getMinXVal() + xInc,
            getMaxXVal() < 0 ? getMaxXVal() - xInc : getMaxXVal() + xInc
          };
          this.zoomDomain(oldYs, newYs, oldXs, newXs);
        }
        mViewManager.invalidateAllViews();
      }
    } else {
      // region selected
      int x = rbRect.x - mLeft - 5;
      int y = rbRect.y - mTop - 5;
      int x2 = x + rbRect.width;
      int y2 = y + rbRect.height;
      Point p1 = new Point();
      Point p2 = new Point();

      if (toolMode == Constants.SELECT_MODE) {
        if (!shiftDown) mCurrPC.unselectAll();

        // construct a search region;
        int[] xpoints = {x, x2, x2, x, x};
        int[] ypoints = {y, y, y2, y2, y};
        Polygon sr = new Polygon(xpoints, ypoints, 5);

        // search for matches
        byte[] currFilterResults = fdm.getResults();
        double[] yArray1 = getYArray1();
        double[] xArray1 = getXArray1();
        double[] yArray2 = getYArray2();
        double[] xArray2 = getXArray2();

        mCurrPC.setBatchModeOn();
        for (int i = 0; i < mCurrPC.getSize(); i++) {
          if (!mIgnoreFilter
              && (mCurrPC.isDeleted(i) || currFilterResults[i] != 4 || !mCurrPC.isSelectedLayer(i)))
            continue;

          double yi = yArray1[i];
          double xi = xArray1[i];
          double xi2 = Float.NaN;
          double yi2 = Float.NaN;
          double xx2 = Float.NaN;
          double yy2 = Float.NaN;

          // correct the X value if necessary
          xi = correctX(xi);

          double xx1 = (xi - winXOrigin) * winXScale;
          double yy1 = (yi - winYOrigin) * winYScale;

          // correct the Y coordinate if necessary
          yy1 = correctY(yy1);

          if (!isYAxisScaler()) {
            yi2 = yArray2[i];
            yy2 = (yi2 - winYOrigin) * winYScale;
            yy2 = correctY(yy2);
          } else yy2 = yy1;

          if (!isXAxisScaler()) {
            xi2 = xArray2[i];
            xi2 = correctX(xi2);
            xx2 = (xi2 - winXOrigin) * winXScale;
          } else xx2 = xx1;

          p1.setLocation((int) xx1, (int) yy1);
          p2.setLocation((int) xx2, (int) yy2);

          if (sr.contains(p1) || sr.contains(p2)) {
            mCurrPC.select(i);
          }
        }
        mViewManager.invalidateAllViews();
        mCurrPC.setBatchModeOff();
      } else if (toolMode == Constants.ZOOM_MODE) {
        // correct the x value if necessary
        double xx = correctX((double) x);
        double xx2 = correctX((double) x2);

        // correct the Y coordinate if necessary
        double yy = correctY((double) y);
        double yy2 = correctY((double) y2);

        double newX = (xx / winXScale) + winXOrigin;
        double newX2 = (xx2 / winXScale) + winXOrigin;
        double newY = (yy / winYScale) + winYOrigin;
        double newY2 = (yy2 / winYScale) + winYOrigin;

        double[] oldYs = {getMaxYVal(), getMinYVal()};
        if (this.toString().indexOf("Depth") >= 0) {
          double temp = newY2;
          newY2 = newY;
          newY = temp;
        }
        double[] newYs = {newY2, newY};

        double[] oldXs = {getMinXVal(), getMaxXVal()};
        double[] newXs = {newX, newX2};
        this.zoomDomain(oldYs, newYs, oldXs, newXs);
        mViewManager.invalidateAllViews();
      }
    }
  }
 void analyzeParticle(int x, int y, ImagePlus imp, ImageProcessor ip) {
   // Wand wand = new Wand(ip);
   ImageProcessor ip2 = redirectIP != null ? redirectIP : ip;
   wand.autoOutline(x, y, level1, level2, wandMode);
   if (wand.npoints == 0) {
     IJ.log("wand error: " + x + " " + y);
     return;
   }
   Roi roi = new PolygonRoi(wand.xpoints, wand.ypoints, wand.npoints, roiType);
   Rectangle r = roi.getBounds();
   if (r.width > 1 && r.height > 1) {
     PolygonRoi proi = (PolygonRoi) roi;
     pf.setPolygon(proi.getXCoordinates(), proi.getYCoordinates(), proi.getNCoordinates());
     ip2.setMask(pf.getMask(r.width, r.height));
     if (floodFill) ff.particleAnalyzerFill(x, y, level1, level2, ip2.getMask(), r);
   }
   ip2.setRoi(r);
   ip.setValue(fillColor);
   ImageStatistics stats = getStatistics(ip2, measurements, calibration);
   boolean include = true;
   if (excludeEdgeParticles) {
     if (r.x == minX || r.y == minY || r.x + r.width == maxX || r.y + r.height == maxY)
       include = false;
     if (polygon != null) {
       Rectangle bounds = roi.getBounds();
       int x1 = bounds.x + wand.xpoints[wand.npoints - 1];
       int y1 = bounds.y + wand.ypoints[wand.npoints - 1];
       int x2, y2;
       for (int i = 0; i < wand.npoints; i++) {
         x2 = bounds.x + wand.xpoints[i];
         y2 = bounds.y + wand.ypoints[i];
         if (!polygon.contains(x2, y2)) {
           include = false;
           break;
         }
         if ((x1 == x2 && ip.getPixel(x1, y1 - 1) == fillColor)
             || (y1 == y2 && ip.getPixel(x1 - 1, y1) == fillColor)) {
           include = false;
           break;
         }
         x1 = x2;
         y1 = y2;
       }
     }
   }
   ImageProcessor mask = ip2.getMask();
   if (minCircularity > 0.0 || maxCircularity < 1.0) {
     double perimeter = roi.getLength();
     double circularity =
         perimeter == 0.0 ? 0.0 : 4.0 * Math.PI * (stats.pixelCount / (perimeter * perimeter));
     if (circularity > 1.0) circularity = 1.0;
     // IJ.log(circularity+"	"+perimeter+"  "+stats.area);
     if (circularity < minCircularity || circularity > maxCircularity) include = false;
   }
   if (stats.pixelCount >= minSize && stats.pixelCount <= maxSize && include) {
     particleCount++;
     if (roiNeedsImage) roi.setImage(imp);
     stats.xstart = x;
     stats.ystart = y;
     saveResults(stats, roi);
     if (showChoice != NOTHING) drawParticle(drawIP, roi, stats, mask);
   }
   if (redirectIP != null) ip.setRoi(r);
   ip.fill(mask);
 }
Example #26
0
 boolean balaColision(Shot shot) {
   if (ovn.contains(shot.x, shot.y)) game.rpr.playBigCrash();
   return ovn.contains(shot.x, shot.y);
 }
Example #27
0
 public boolean containsPoint(Point p) {
   for (Polygon poly : getWireframe()) if (poly.contains(p)) return true;
   return false;
 }
  public void runStuff(
      DimensionMap map,
      TreeMap<DimensionMap, ROIPlus> maximaMap,
      TreeMap<DimensionMap, String> segMap,
      TreeMap<DimensionMap, String> maskMap,
      TreeMap<DimensionMap, String> imageMap,
      TreeMap<DimensionMap, Double> results,
      Canceler canceler) {
    // Get the Maxima
    ROIPlus maxima = maximaMap.get(map);

    // Make the mask image impMask
    // ByteProcessor impMask = (ByteProcessor) (new
    // ImagePlus(maskMap.get(map)).getProcessor().convertToByte(false));
    // ByteProcessor impSeg = (ByteProcessor) (new
    // ImagePlus(segMap.get(map)).getProcessor().convertToByte(false));
    ByteProcessor impSeg = (ByteProcessor) (new ImagePlus(segMap.get(map))).getProcessor();
    ByteProcessor impMask = (ByteProcessor) (new ImagePlus(maskMap.get(map))).getProcessor();
    ByteBlitter blit = new ByteBlitter(impSeg);
    blit.copyBits(impMask, 0, 0, Blitter.AND);
    FloatProcessor impImage =
        (FloatProcessor) (new ImagePlus(imageMap.get(map))).getProcessor().convertToFloat();
    Wand wand = new Wand(impSeg);
    Wand wand2 = new Wand(impMask);
    Vector<Double> measurements;
    for (IdPoint p : maxima.getPointList()) {
      if (canceler.isCanceled()) {
        return;
      }
      if (impSeg.getPixel(p.x, p.y)
          == 255) // if we land on a cell that made it through thresholding
      {
        wand.autoOutline(p.x, p.y); // outline it
        wand2.autoOutline(p.x, p.y);
        boolean partOfCellClump =
            !this.selectionsAreEqual(
                wand,
                wand2); // If the segmented and unsegmented masks do not agree on the roi, then this
        // cell is part of a clump.
        if (wand.npoints > 0) {
          Roi roi =
              new PolygonRoi(
                  wand.xpoints,
                  wand.ypoints,
                  wand.npoints,
                  Roi.POLYGON); // The roi helps for using getLength() (DON'T USE Roi.TRACED_ROI.,
          // IT SCREWS UP THE Polygon OBJECTS!!!! Bug emailed to ImageJ
          // folks)
          Polygon poly =
              new Polygon(
                  wand.xpoints,
                  wand.ypoints,
                  wand.npoints); // The polygon helps for using contains()
          Rectangle r = roi.getBounds();
          measurements = new Vector<Double>();
          for (int i = r.x; i < r.x + r.width; i++) {
            for (int j = r.y; j < r.y + r.height; j++) {
              // innerBoundary
              if (poly.contains(i, j) && impSeg.getPixelValue(i, j) == 255) {
                measurements.add((double) impImage.getPixelValue(i, j));
                // Logs.log("In - " + innerT, this);
              }
            }
          }

          impMask.setRoi(roi);
          ImageStatistics stats =
              ImageStatistics.getStatistics(
                  impMask,
                  ImageStatistics.AREA
                      & ImageStatistics.PERIMETER
                      & ImageStatistics.CIRCULARITY
                      & ImageStatistics.ELLIPSE,
                  null);
          if (measurements.size() > 0) {
            DimensionMap resultsMap = map.copy();
            resultsMap.put("Id", "" + p.id);

            resultsMap.put("Measurement", "X");
            results.put(resultsMap.copy(), (double) p.x);
            resultsMap.put("Measurement", "Y");
            results.put(resultsMap.copy(), (double) p.y);
            resultsMap.put("Measurement", "AREA");
            results.put(resultsMap.copy(), stats.area);
            resultsMap.put("Measurement", "PERIMETER");
            results.put(resultsMap.copy(), roi.getLength());
            resultsMap.put("Measurement", "CIRCULARITY");
            results.put(
                resultsMap.copy(), 4.0 * Math.PI * (stats.area / (Math.pow(roi.getLength(), 2))));
            resultsMap.put("Measurement", "ELLIPSE MAJOR");
            results.put(resultsMap.copy(), stats.major);
            resultsMap.put("Measurement", "ELLIPSE MINOR");
            results.put(resultsMap.copy(), stats.minor);
            resultsMap.put("Measurement", "MEAN");
            results.put(resultsMap.copy(), StatisticsUtility.mean(measurements));
            resultsMap.put("Measurement", "MEDIAN");
            results.put(resultsMap.copy(), StatisticsUtility.median(measurements));
            resultsMap.put("Measurement", "SUM");
            results.put(resultsMap.copy(), StatisticsUtility.sum(measurements));
            resultsMap.put("Measurement", "MIN");
            results.put(resultsMap.copy(), StatisticsUtility.min(measurements));
            resultsMap.put("Measurement", "MAX");
            results.put(resultsMap.copy(), StatisticsUtility.max(measurements));
            resultsMap.put("Measurement", "STDDEV");
            results.put(resultsMap.copy(), StatisticsUtility.stdDev(measurements));
            resultsMap.put("Measurement", "VARIANCE");
            results.put(resultsMap.copy(), StatisticsUtility.variance(measurements));
            resultsMap.put("Measurement", "CLUMP");
            results.put(resultsMap.copy(), (double) (partOfCellClump ? 1 : 0));
          }
        }
      }
    }
  }
Example #29
0
 public boolean contains(Player b) {
   return poly.contains(b.getRectangle());
 }
Example #30
0
  public void processPolygonSpline(boolean shiftDown) {
    mCurrPC.setBatchModeOn();
    if (!shiftDown) mCurrPC.unselectAll();

    // loop on spline pts to construct a Polygon
    Polygon srcArea = new Polygon();
    for (int s = 0; s < mSplinePoints.size(); s++) {
      Point p = (Point) mSplinePoints.elementAt(s);
      int x = p.x - mLeft - 5;
      int y = p.y - mTop - 5;

      srcArea.addPoint(x, y);
    }

    mSplinePoints.removeAllElements();

    // search for matches
    byte[] currFilterResults = fdm.getResults();
    double[] yArray1 = getYArray1();
    double[] xArray1 = getXArray1();
    double[] yArray2 = getYArray2();
    double[] xArray2 = getXArray2();
    Point p1 = new Point();
    Point p2 = new Point();

    for (int i = 0; i < mCurrPC.getSize(); i++) {
      if (!mIgnoreFilter
          && (mCurrPC.isDeleted(i) || currFilterResults[i] != 4 || !mCurrPC.isSelectedLayer(i)))
        continue;
      double yi = yArray1[i];
      double xi = xArray1[i];
      double xi2 = Float.NaN;
      double yi2 = Float.NaN;
      double xx2 = Float.NaN;
      double yy2 = Float.NaN;

      // correct the X value if necessary
      xi = correctX(xi);

      double xx1 = (xi - winXOrigin) * winXScale;
      double yy1 = (yi - winYOrigin) * winYScale;

      // correct the Y coordinate if necessary
      yy1 = correctY(yy1);

      if (!isYAxisScaler()) {
        yi2 = yArray2[i];
        yy2 = (yi2 - winYOrigin) * winYScale;
        ;
        yy2 = correctY(yy2);
      } else yy2 = yy1;

      if (!isXAxisScaler()) {
        xi2 = xArray2[i];
        xi2 = correctX(xi2);
        xx2 = (xi2 - winXOrigin) * winXScale;
      } else xx2 = xx1;

      p1.setLocation((int) xx1, (int) yy1);
      p2.setLocation((int) xx2, (int) yy2);

      if (srcArea.contains(p1) || srcArea.contains(p2)) {
        mCurrPC.select(i);
      }
    }
    mViewManager.invalidateAllViews();
    mCurrPC.setBatchModeOff();
  }