projectionFactor method
Computes the Projection Factor for the projection of the point p onto this LineSegment. The Projection Factor is the constant r by which the vector for this segment must be multiplied to equal the vector for the projection of p on the line defined by this segment.
The projection factor will lie in the range (-inf, +inf),
or be NaN
if the line segment has zero length..
@param p the point to compute the factor for @return the projection factor for the point
Implementation
double projectionFactor(Coordinate p) {
if (p.equals(p0)) return 0.0;
if (p.equals(p1)) return 1.0;
// Otherwise, use comp.graphics.algorithms Frequently Asked Questions method
/* AC dot AB
r = ---------
||AB||^2
r has the following meaning:
r=0 P = A
r=1 P = B
r<0 P is on the backward extension of AB
r>1 P is on the forward extension of AB
0<r<1 P is interior to AB
*/
double dx = p1.x - p0.x;
double dy = p1.y - p0.y;
double len = dx * dx + dy * dy;
// handle zero-length segments
if (len <= 0.0) return double.nan;
double r = ((p.x - p0.x) * dx + (p.y - p0.y) * dy) / len;
return r;
}