Java Code Examples for java.awt.geom.Point2D#distance()

The following examples show how to use java.awt.geom.Point2D#distance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SegmentSorter.java    From maze-harvester with GNU General Public License v3.0 5 votes vote down vote up
private static List<Line2D> quadraticSort(ImmutableList<Line2D> input) {
  ArrayList<Line2D> segments = new ArrayList<>(input);
  ArrayList<Line2D> output = new ArrayList<>();

  // Pick the first segment arbitrarily.
  Line2D nextSegment = segments.remove(0);
  output.add(nextSegment);

  // Now find nearby segments with scans of the segments array. O(n^2)!
  while (segments.size() > 0) {
    Point2D currentPen = nextSegment.getP2();

    int bestIndex = 0;
    int bestDirection = 0;
    double bestDistance = Double.MAX_VALUE;
    
    for (int i=0; i<segments.size(); i++) {
      Line2D thisLine = segments.get(i);
      for (int direction = 0; direction < 2; direction++) {
        Point2D thisPoint = direction==0 ? thisLine.getP1() : thisLine.getP2();
        double thisDistance = currentPen.distance(thisPoint);
        if (thisDistance < bestDistance) {
          bestIndex = i;
          bestDirection = direction;
          bestDistance = thisDistance;
        }
      }
    }

    nextSegment = segments.remove(bestIndex);
    if (bestDirection == 1) {
      nextSegment = new Line2D.Double(nextSegment.getP2(), nextSegment.getP1());
    }
    output.add(nextSegment);
  }
  return output;
}
 
Example 2
Source File: PainterGenerator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private String encodeRadial(Shape ps, RadialGradient g) {
    float centerX1 = (float)ps.getPaintX1();
    float centerY1 = (float)ps.getPaintY1();
    float x2 = (float)ps.getPaintX2();
    float y2 = (float)ps.getPaintY2();
    float radius = (float)Point2D.distance(centerX1, centerY1, x2, y2);
    StringBuilder b = new StringBuilder();

    b.append("        return decodeRadialGradient((");
    b.append(centerX1);
    b.append("f * w) + x, (");
    b.append(centerY1);
    b.append("f * h) + y, ");
    b.append(radius);
    b.append("f,\n");
    encodeGradientColorsAndFractions(g,b);
    b.append(");");

    String methodBody = b.toString();
    String methodName = methods.get(methodBody);
    if (methodName == null) {
        methodName = "decodeRadial" + radialCounter++;
        gradientsCode.append("    private Paint ").append(methodName).append("(Shape s) {\n");
        gradientsCode.append("        Rectangle2D bounds = s.getBounds2D();\n");
        gradientsCode.append("        float x = (float)bounds.getX();\n");
        gradientsCode.append("        float y = (float)bounds.getY();\n");
        gradientsCode.append("        float w = (float)bounds.getWidth();\n");
        gradientsCode.append("        float h = (float)bounds.getHeight();\n");
        gradientsCode.append(methodBody);
        gradientsCode.append("\n    }\n\n");
        methods.put(methodBody, methodName);
    }
    return methodName;
}
 
Example 3
Source File: CollinearPoints.java    From Algorithms with MIT License 5 votes vote down vote up
public static int collinear(Point2D a, Point2D b, Point2D c) {

    if (a.distance(b) < EPS) throw new IllegalArgumentException("a cannot equal b");

    // To determine if c is on the line we will use the determinant of
    // the two vectors formed by 'ab' and 'ac' (could also have done 'ba' and 'bc').
    // The determinant is a particularly useful property in linear algebra because
    // it can tell us the signed area of a parallelogram between two vectors.
    // Furthermore, we know that two vectors are parallel if the area of the
    // parallelogram between them is zero and we will use this fact to determine
    // if the point c is on the line formed by a & b

    // If a = (a_x, a_y), b = (b_x, b_y), c = (c_x, c_y) then our two vectors
    // 'ab' and 'ac' are v1 = <b_x-a_x, b_y-a_y> and v2 = <c_x-a_x, c_y-a_y>
    double v1_x = b.getX() - a.getX();
    double v1_y = b.getY() - a.getY();
    double v2_x = c.getX() - a.getX();
    double v2_y = c.getY() - a.getY();

    //                                                           | v1_x v2_x |
    // When we place our two vectors inside a 2x2 matrix we get: | v1_y v2_y |, and
    // hence we get that the determinant is (v1_x*v2_y)-(v2_x*v1_y)
    double determinant = (v1_x * v2_y) - (v2_x * v1_y);

    // The points a, b, c are collinear
    if (abs(determinant) < EPS) return 0;

    // Return -1 for right and +1 for left
    return (determinant < 0 ? -1 : +1);
  }
 
Example 4
Source File: PainterGenerator.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private String encodeRadial(Shape ps, RadialGradient g) {
    float centerX1 = (float)ps.getPaintX1();
    float centerY1 = (float)ps.getPaintY1();
    float x2 = (float)ps.getPaintX2();
    float y2 = (float)ps.getPaintY2();
    float radius = (float)Point2D.distance(centerX1, centerY1, x2, y2);
    StringBuilder b = new StringBuilder();

    b.append("        return decodeRadialGradient((");
    b.append(centerX1);
    b.append("f * w) + x, (");
    b.append(centerY1);
    b.append("f * h) + y, ");
    b.append(radius);
    b.append("f,\n");
    encodeGradientColorsAndFractions(g,b);
    b.append(");");

    String methodBody = b.toString();
    String methodName = methods.get(methodBody);
    if (methodName == null) {
        methodName = "decodeRadial" + radialCounter++;
        gradientsCode.append("    private Paint ").append(methodName).append("(Shape s) {\n");
        gradientsCode.append("        Rectangle2D bounds = s.getBounds2D();\n");
        gradientsCode.append("        float x = (float)bounds.getX();\n");
        gradientsCode.append("        float y = (float)bounds.getY();\n");
        gradientsCode.append("        float w = (float)bounds.getWidth();\n");
        gradientsCode.append("        float h = (float)bounds.getHeight();\n");
        gradientsCode.append(methodBody);
        gradientsCode.append("\n    }\n\n");
        methods.put(methodBody, methodName);
    }
    return methodName;
}
 
Example 5
Source File: MultiGradientTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
private void updatePoints(int x, int y) {
    Point2D inv = new Point2D.Double(x, y);

    try {
        inv = transform.inverseTransform(inv, null);
    } catch (NoninvertibleTransformException e) {
        e.printStackTrace();
    }

    x = (int)inv.getX();
    y = (int)inv.getY();

    switch (paintType) {
    default:
    case BASIC:
    case LINEAR:
        // pick the closest point to move
        if (inv.distance(startX, startY) < inv.distance(endX, endY)) {
            startX = x;
            startY = y;
        } else {
            endX = x;
            endY = y;
        }
        break;

    case RADIAL:
        // pick the closest point to move
        if (inv.distance(ctrX, ctrY) < inv.distance(focusX, focusY)) {
            ctrX = x;
            ctrY = y;
        } else {
            focusX = x;
            focusY = y;
        }
        break;
    }

    updatePaint();
}
 
Example 6
Source File: MultiGradientTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void updatePoints(int x, int y) {
    Point2D inv = new Point2D.Double(x, y);

    try {
        inv = transform.inverseTransform(inv, null);
    } catch (NoninvertibleTransformException e) {
        e.printStackTrace();
    }

    x = (int)inv.getX();
    y = (int)inv.getY();

    switch (paintType) {
    default:
    case BASIC:
    case LINEAR:
        // pick the closest point to move
        if (inv.distance(startX, startY) < inv.distance(endX, endY)) {
            startX = x;
            startY = y;
        } else {
            endX = x;
            endY = y;
        }
        break;

    case RADIAL:
        // pick the closest point to move
        if (inv.distance(ctrX, ctrY) < inv.distance(focusX, focusY)) {
            ctrX = x;
            ctrY = y;
        } else {
            focusX = x;
            focusY = y;
        }
        break;
    }

    updatePaint();
}
 
Example 7
Source File: DtdStateSupervisor.java    From workcraft with MIT License 5 votes vote down vote up
private void limitSignalEventPosition(VisualEvent event, double xMin, double xMax) {
    Rectangle2D bb = event.getBoundingBox();
    double x = event.getX();
    if (bb.getMinX() < xMin) {
        x = xMin + event.getX() - bb.getMinX();
    } else if (bb.getMaxX() > xMax) {
        x = xMax - bb.getMaxX() + event.getX();
    }
    Point2D pos = new Point2D.Double(x, 0.0);
    if (pos.distance(event.getPosition()) > 0.001) {
        event.setPosition(pos);
    }
}
 
Example 8
Source File: ConnectionHelper.java    From workcraft with MIT License 5 votes vote down vote up
public static void removeControlPointsByDistance(Polyline polyline, Point2D pos, double threshold) {
    List<ControlPoint> controlPoints = new LinkedList<>(polyline.getControlPoints());
    for (ControlPoint cp:  controlPoints) {
        Point2D curPos = cp.getPosition();
        if (curPos.distance(pos) < threshold) {
            polyline.remove(cp);
        }
    }
}
 
Example 9
Source File: Polyline.java    From workcraft with MIT License 5 votes vote down vote up
public int getNearestSegment(Point2D pt, Point2D outPointOnSegment) {
    double min = Double.MAX_VALUE;
    int nearest = -1;

    for (int i = 0; i < getSegmentCount(); i++) {
        Line2D segment = getSegment(i);
        Point2D a = new Point2D.Double(pt.getX() - segment.getX1(), pt.getY() - segment.getY1());
        Point2D b = new Point2D.Double(segment.getX2() - segment.getX1(), segment.getY2() - segment.getY1());

        double magB = b.distance(0, 0);
        double dist;
        if (magB < 0.0000001) {
            dist = pt.distance(segment.getP1());
        } else {
            b.setLocation(b.getX() / magB, b.getY() / magB);
            double magAonB = a.getX() * b.getX() + a.getY() * b.getY();
            if (magAonB < 0) {
                magAonB = 0;
            }
            if (magAonB > magB) {
                magAonB = magB;
            }
            a.setLocation(segment.getX1() + b.getX() * magAonB, segment.getY1() + b.getY() * magAonB);
            dist = new Point2D.Double(pt.getX() - a.getX(), pt.getY() - a.getY()).distance(0, 0);
        }

        if (dist < min) {
            min = dist;
            if (outPointOnSegment != null) {
                outPointOnSegment.setLocation(a);
            }
            nearest = i;
        }
    }
    return nearest;
}
 
Example 10
Source File: ConnectionHelper.java    From workcraft with MIT License 5 votes vote down vote up
private static void filterControlPointsByDistance(Polyline polyline, Point2D startPos, double threshold, boolean reverse) {
    List<ControlPoint> controlPoints = new LinkedList<>(polyline.getControlPoints());
    if (reverse) {
        Collections.reverse(controlPoints);
    }
    Point2D predPos = startPos;
    for (ControlPoint cp:  controlPoints) {
        Point2D curPos = cp.getPosition();
        if (curPos.distance(predPos) < threshold) {
            polyline.remove(cp);
        } else {
            predPos = curPos;
        }
    }
}
 
Example 11
Source File: MultiGradientTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void updatePoints(int x, int y) {
    Point2D inv = new Point2D.Double(x, y);

    try {
        inv = transform.inverseTransform(inv, null);
    } catch (NoninvertibleTransformException e) {
        e.printStackTrace();
    }

    x = (int)inv.getX();
    y = (int)inv.getY();

    switch (paintType) {
    default:
    case BASIC:
    case LINEAR:
        // pick the closest point to move
        if (inv.distance(startX, startY) < inv.distance(endX, endY)) {
            startX = x;
            startY = y;
        } else {
            endX = x;
            endY = y;
        }
        break;

    case RADIAL:
        // pick the closest point to move
        if (inv.distance(ctrX, ctrY) < inv.distance(focusX, focusY)) {
            ctrX = x;
            ctrY = y;
        } else {
            focusX = x;
            focusY = y;
        }
        break;
    }

    updatePaint();
}
 
Example 12
Source File: RightAngleBoxContainerPanelUI.java    From pumpernickel with MIT License 5 votes vote down vote up
private Point2D midway(Point2D p1, Point2D p2, double distance) {
	double theta = Math.atan2(p2.getY() - p1.getY(),
			p2.getX() - p1.getX());
	double maxDistance = p1.distance(p2);
	if (distance < 0)
		distance = 0;
	if (distance > maxDistance)
		distance = maxDistance;
	return new Point2D.Double(p1.getX() + distance * Math.cos(theta),
			p1.getY() + distance * Math.sin(theta));
}
 
Example 13
Source File: mxOrganicLayout.java    From blog-codes with Apache License 2.0 5 votes vote down vote up
/**
 * This method calculates the energy due to the length of the specified
 * edge. The energy is proportional to the length of the edge, making
 * shorter edges preferable in the layout.
 * 
 * @param i the index of the edge in the array <code>e</code>
 * @return the total edge length energy of the specified edge 
 */
protected double getEdgeLength(int i)
{
	if (isOptimizeEdgeLength)
	{
		double edgeLength = Point2D.distance(v[e[i].source].x,
				v[e[i].source].y, v[e[i].target].x, v[e[i].target].y);
		return (edgeLengthCostFactor * edgeLength * edgeLength);
	}
	else
	{
		return 0.0;
	}
}
 
Example 14
Source File: DiscretizedLocationOperator.java    From beast-mcmc with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<Point2D, List<WeightedPoint2D>> makeNearestNeighborMap() {
        Map<Point2D, List<WeightedPoint2D>> map = new HashMap<Point2D, List<WeightedPoint2D>>();

        for (Point2D location : allLocations) {

            List<WeightedPoint2D> weightedNeighbors = new ArrayList<WeightedPoint2D>();
            for (Point2D neighbor : allLocations) {
                double distance = location.distance(neighbor);
                if (distance > 0)
                    weightedNeighbors.add(
                            new WeightedPoint2D(neighbor.getX(), neighbor.getY(), distance)
                    );
            }
            Collections.sort(weightedNeighbors);

            map.put(location, weightedNeighbors);
        }

//        for (Point2D location : map.keySet()) {
//            List<WeightedPoint2D> neighbors = map.get(location);
//            System.err.println("Location: "+location+"\n");
//            System.err.println("\t");
//            int count = 0;
//            for (WeightedPoint2D neighbor : neighbors) {
//                count++;
//                if (count < 3)
//                    System.err.println(" "+neighbor);
//            }
//            System.err.println("\n");
//        }

        return map;
    }
 
Example 15
Source File: MinimumCostConvexPolygonTriangulation.java    From Algorithms with MIT License 4 votes vote down vote up
private static double cost(Point2D i, Point2D j, Point2D k) {
  return i.distance(j) + i.distance(k) + j.distance(k);
}
 
Example 16
Source File: TransportWizard.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Check if the building template is outside minimum radius and within the maximum radius
 * @param bt the building template
 * @param buildingManager buildingManager
 * @return true if it's within the prescribed zone
 */
public boolean isWithinZone(BuildingTemplate bt, BuildingManager buildingManager) {

   	boolean withinRadius = true;
   	int maxDistance = 0;
   	int leastDistance = 0;
   	// TOD: also check if
   	boolean hasLifeSupport = buildingConfig.hasLifeSupport(bt.getBuildingType());
   	if (hasLifeSupport) {

   	  	if (bt.getBuildingType().equalsIgnoreCase("Astronomy Observatory")) {
   	  		maxDistance = Resupply.MAX_OBSERVATORY_BUILDING_DISTANCE;
   	  		leastDistance = Resupply.MIN_OBSERVATORY_BUILDING_DISTANCE;
   	  	}
   	  	else {
       		maxDistance = Resupply.MAX_INHABITABLE_BUILDING_DISTANCE;
       		leastDistance = Resupply.MIN_INHABITABLE_BUILDING_DISTANCE;
   	  	}

   	}

   	else {
   		maxDistance = Resupply.MAX_NONINHABITABLE_BUILDING_DISTANCE;
   		leastDistance = Resupply.MIN_NONINHABITABLE_BUILDING_DISTANCE;
   	}

   	List<Building> list = buildingManager.getBuildings(FunctionType.LIFE_SUPPORT);
       Collections.shuffle(list);

       Iterator<Building> i = list.iterator();
       while (i.hasNext()) {
           Building startingBuilding = i.next();

           double distance = Point2D.distance(startingBuilding.getXLocation(), startingBuilding.getYLocation(),
           		bt.getXLoc(), bt.getYLoc());
           //logger.info("distance : " + distance);
           if (distance < leastDistance) {
           	withinRadius = false;
           	break;
           }
       }

    return withinRadius;
}
 
Example 17
Source File: NumberAxis3D.java    From orson-charts with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Selects a tick size that is appropriate for drawing the axis from
 * {@code pt0} to {@code pt1}.
 * 
 * @param g2  the graphics target ({@code null} not permitted).
 * @param pt0  the starting point for the axis.
 * @param pt1  the ending point for the axis.
 * @param opposingPt  a point on the opposite side of the line from where
 *     the labels should be drawn.
 */
@Override
public double selectTick(Graphics2D g2, Point2D pt0, Point2D pt1, 
        Point2D opposingPt) {
    
    if (this.tickSelector == null) {
        return this.tickSize;
    }
    g2.setFont(getTickLabelFont()); 
    FontMetrics fm = g2.getFontMetrics(getTickLabelFont());        
    double length = pt0.distance(pt1);
    LabelOrientation orientation = getTickLabelOrientation();
    if (orientation.equals(LabelOrientation.PERPENDICULAR)) {
        // based on the font height, we can determine roughly how many tick
        // labels will fit in the length available
        double height = fm.getHeight();
        // the tickLabelFactor allows some control over how dense the labels
        // will be
        int maxTicks = (int) (length / (height * getTickLabelFactor()));
        if (maxTicks > 2 && this.tickSelector != null) {
            double rangeLength = getRange().getLength();
            this.tickSelector.select(rangeLength / 2.0);
            // step through until we have too many ticks OR we run out of 
            // tick sizes
            int tickCount = (int) (rangeLength 
                    / this.tickSelector.getCurrentTickSize());
            while (tickCount < maxTicks) {
                this.tickSelector.previous();
                tickCount = (int) (rangeLength
                        / this.tickSelector.getCurrentTickSize());
            }
            this.tickSelector.next();
            this.tickSize = this.tickSelector.getCurrentTickSize();
            // TFE, 20180911: don't overwrite any formatter explicitly set
            if (DEFAULT_TICK_LABEL_FORMATTER.equals(this.tickLabelFormatter)) {
                this.tickLabelFormatter 
                        = this.tickSelector.getCurrentTickLabelFormat();
            }
        } else {
            this.tickSize = Double.NaN;
        }
    } else if (orientation.equals(LabelOrientation.PARALLEL)) {
        // choose a unit that is at least as large as the length of the axis
        this.tickSelector.select(getRange().getLength());
        boolean done = false;
        while (!done) {
            if (this.tickSelector.previous()) {
                // estimate the label widths, and do they overlap?
                Format f = this.tickSelector.getCurrentTickLabelFormat();
                String s0 = f.format(this.range.getMin());
                String s1 = f.format(this.range.getMax());
                double w0 = fm.stringWidth(s0);
                double w1 = fm.stringWidth(s1);
                double w = Math.max(w0, w1);
                int n = (int) (length / (w * this.getTickLabelFactor()));
                if (n < getRange().getLength() 
                        / tickSelector.getCurrentTickSize()) {
                    tickSelector.next();
                    done = true;
                }
            } else {
                done = true;
            }
        }
        this.tickSize = this.tickSelector.getCurrentTickSize();
        // TFE, 20180911: don't overwrite any formatter explicitly set
        if (DEFAULT_TICK_LABEL_FORMATTER.equals(this.tickLabelFormatter)) {
            this.tickLabelFormatter 
                    = this.tickSelector.getCurrentTickLabelFormat();
        }
    }
    return this.tickSize;
}
 
Example 18
Source File: StandardCategoryAxis3D.java    From orson-charts with GNU General Public License v3.0 4 votes vote down vote up
private double drawParallelTickLabels(Graphics2D g2, Line2D axisLine,
        Point2D opposingPt, List<TickData> tickData, 
        double maxTickLabelWidth, RenderingInfo info, boolean hinting) {
    int levels = 1;
    LineMetrics lm = g2.getFontMetrics().getLineMetrics("123", g2);
    double height = lm.getHeight();
    if (tickData.size() > 1) {
    
        // work out how many offset levels we need to display the 
        // categories without overlapping
        Point2D p0 = tickData.get(0).getAnchorPt();
        Point2D pN = tickData.get(tickData.size() - 1).getAnchorPt();
        double availableWidth = pN.distance(p0) 
                * tickData.size() / (tickData.size() - 1);
        int labelsPerLevel = (int) Math.floor(availableWidth / 
                (maxTickLabelWidth * tickLabelFactor));
        int levelsRequired = this.maxTickLabelLevels;
        if (labelsPerLevel > 0) {
            levelsRequired = this.categories.size() / labelsPerLevel + 1;
        }
        levels = Math.min(levelsRequired, this.maxTickLabelLevels);
    }
    
    int index = 0;
    for (TickData t : tickData) {
        int level = index % levels;
        double adj = height * (level + 0.5);
        Line2D perpLine = Utils2D.createPerpendicularLine(axisLine, 
                t.getAnchorPt(), this.tickMarkLength 
                + this.tickLabelOffset + adj, opposingPt);
        double axisTheta = Utils2D.calculateTheta(axisLine);
        TextAnchor textAnchor = TextAnchor.CENTER;
        if (axisTheta >= Math.PI / 2.0) {
            axisTheta = axisTheta - Math.PI;
        } else if (axisTheta <= -Math.PI / 2) {
            axisTheta = axisTheta + Math.PI;  
        }
        String tickLabel = t.getKeyLabel();
        if (hinting) {
            Map<String, String> m = new HashMap<>();
            m.put("ref", "{\"type\": \"categoryTickLabel\", \"axis\": \"" 
                    + axisStr() + "\", \"key\": \"" 
                    + t.getKey() + "\"}");
            g2.setRenderingHint(Chart3DHints.KEY_BEGIN_ELEMENT, m);
        }

        Shape bounds = TextUtils.drawRotatedString(tickLabel, g2, 
                (float) perpLine.getX2(), (float) perpLine.getY2(), 
                textAnchor, axisTheta, textAnchor);
        if (hinting) {
            g2.setRenderingHint(Chart3DHints.KEY_END_ELEMENT, true);
        }
        if (info != null) {
            RenderedElement tickLabelElement = new RenderedElement(
                    InteractiveElementType.CATEGORY_AXIS_TICK_LABEL, bounds);
            tickLabelElement.setProperty("label", tickLabel);
            tickLabelElement.setProperty("axis", axisStr());
            info.addOffsetElement(tickLabelElement);
        }
        index++;
    }
    return height * levels;
}
 
Example 19
Source File: TransportWizard.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Check if the new building is outside minimum radius and within the maximum radius
 * @param newBuilding the new building
 * @param mgr the building manager
 * @return true if it's within the prescribed zone
 */
public boolean isWithinZone(Building newBuilding, BuildingManager mgr) {

   	boolean withinRadius = true;
   	int maxDistance = 0;
   	int leastDistance = 0;
   	// TOD: also check if
   	boolean hasLifeSupport = buildingConfig.hasLifeSupport(newBuilding.getBuildingType());
   	if (hasLifeSupport) {

   	  	if (newBuilding.getBuildingType().equalsIgnoreCase("Astronomy Observatory")) {
   	  		maxDistance = Resupply.MAX_OBSERVATORY_BUILDING_DISTANCE;
   	  		leastDistance = Resupply.MIN_OBSERVATORY_BUILDING_DISTANCE;
   	  	}
   	  	else {
       		maxDistance = Resupply.MAX_INHABITABLE_BUILDING_DISTANCE;
       		leastDistance = Resupply.MIN_INHABITABLE_BUILDING_DISTANCE;
   	  	}

   	}

   	else {
   		maxDistance = Resupply.MAX_NONINHABITABLE_BUILDING_DISTANCE;
   		leastDistance = Resupply.MIN_NONINHABITABLE_BUILDING_DISTANCE;
   	}

   	List<Building> list = mgr.getBuildings(FunctionType.LIFE_SUPPORT);
       Collections.shuffle(list);

       Iterator<Building> i = list.iterator();
       while (i.hasNext()) {
           Building startingBuilding = i.next();

           double distance = Point2D.distance(startingBuilding.getXLocation(),
               startingBuilding.getYLocation(), newBuilding.getXLocation(),
               newBuilding.getYLocation());
           //logger.info("distance : " + distance);
           if (distance < leastDistance) {
           	withinRadius = false;
           	break;
           }
       }


    return withinRadius;
}
 
Example 20
Source File: LogAxis3D.java    From orson-charts with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Selects a standard tick unit on the logarithmic range.
 * 
 * @param g2  the graphics target ({@code null} not permitted).
 * @param pt0  the starting point.
 * @param pt1  the ending point.
 * @param opposingPt  an opposing point.
 * 
 * @return The tick unit (log increment).
 */
@Override
public double selectTick(Graphics2D g2, Point2D pt0, Point2D pt1, 
        Point2D opposingPt) {
 
    if (this.tickSelector == null) {
        return this.tickSize;
    }
    g2.setFont(getTickLabelFont());
    FontMetrics fm = g2.getFontMetrics();
    double length = pt0.distance(pt1);
    double rangeLength = this.logRange.getLength();
    
    LabelOrientation orientation = getTickLabelOrientation();
    if (orientation.equals(LabelOrientation.PERPENDICULAR)) {
        // based on the font height, we can determine roughly how many tick
        // labels will fit in the length available
        int height = fm.getHeight();
        // the tickLabelFactor allows some control over how dense the labels
        // will be
        int maxTicks = (int) (length / (height * getTickLabelFactor()));
        if (maxTicks > 2 && this.tickSelector != null) {
            this.tickSelector.select(rangeLength / 2.0);
            // step through until we have too many ticks OR we run out of 
            // tick sizes
            int tickCount = (int) (rangeLength 
                    / this.tickSelector.getCurrentTickSize());
            while (tickCount < maxTicks) {
                this.tickSelector.previous();
                tickCount = (int) (rangeLength
                        / this.tickSelector.getCurrentTickSize());
            }
            this.tickSelector.next();
            this.tickSize = this.tickSelector.getCurrentTickSize();
            this.tickLabelFormatter 
                    = this.tickSelector.getCurrentTickLabelFormat();
        } else { 
            this.tickSize = Double.NaN;
        }
    } else if (orientation.equals(LabelOrientation.PARALLEL)) {
        // choose a unit that is at least as large as the length of the axis
        this.tickSelector.select(rangeLength);
        boolean done = false;
        while (!done) {
            if (this.tickSelector.previous()) {
                // estimate the label widths, and do they overlap?
                AttributedString s0 = createTickLabelAttributedString(
                        this.logRange.getMax() + this.logRange.getMin(), 
                        this.tickSelector.getCurrentTickLabelFormat());
                TextLayout layout0 = new TextLayout(s0.getIterator(), 
                        g2.getFontRenderContext());
                double w0 = layout0.getAdvance();
                AttributedString s1 = createTickLabelAttributedString(
                        this.logRange.getMax() + this.logRange.getMin(), 
                        this.tickSelector.getCurrentTickLabelFormat());
                TextLayout layout1 = new TextLayout(s1.getIterator(), 
                        g2.getFontRenderContext());
                double w1 = layout1.getAdvance();
                double w = Math.max(w0, w1);
                int n = (int) (length / (w * this.getTickLabelFactor()));
                if (n < rangeLength 
                        / tickSelector.getCurrentTickSize()) {
                    tickSelector.next();
                    done = true;
                }
            } else {
                done = true;
            }
        }
        this.tickSize = this.tickSelector.getCurrentTickSize();
        this.tickLabelFormatter 
                = this.tickSelector.getCurrentTickLabelFormat();
    }
    return this.tickSize;
}