computeEdgeDistance static method

double computeEdgeDistance(
  1. Coordinate p,
  2. Coordinate p0,
  3. Coordinate p1
)

Computes the "edge distance" of an intersection point p along a segment. The edge distance is a metric of the point along the edge. The metric used is a robust and easy to compute metric function. It is not equivalent to the usual Euclidean metric. It relies on the fact that either the x or the y ordinates of the points in the edge are unique, depending on whether the edge is longer in the horizontal or vertical direction.

NOTE: This function may produce incorrect distances for inputs where p is not precisely on p1-p2 (E.g. p = (139,9) p1 = (139,10), p2 = (280,1) produces distance 0.0, which is incorrect.

My hypothesis is that the function is safe to use for points which are the result of rounding points which lie on the line, but not safe to use for truncated points.

Implementation

static double computeEdgeDistance(
    Coordinate p, Coordinate p0, Coordinate p1) {
  double dx = (p1.x - p0.x).abs();
  double dy = (p1.y - p0.y).abs();

  double dist = -1.0; // sentinel value
  if (p.equals(p0)) {
    dist = 0.0;
  } else if (p.equals(p1)) {
    if (dx > dy)
      dist = dx;
    else
      dist = dy;
  } else {
    double pdx = (p.x - p0.x).abs();
    double pdy = (p.y - p0.y).abs();
    if (dx > dy)
      dist = pdx;
    else
      dist = pdy;
    // <FIX>
    // hack to ensure that non-endpoints always have a non-zero distance
    if (dist == 0.0 && !p.equals(p0)) {
      dist = math.max(pdx, pdy);
    }
  }
  //TODO Assert.isTrue(! (dist == 0.0 && ! p.equals(p0)), "Bad distance calculation");
  return dist;
}