GRASS Programmer's Manual  6.5.svn(2014)-r66266
gis/line_dist.c
Go to the documentation of this file.
1 #include <grass/gis.h>
2 /* compute square of distance of point (x,y) to line segment (x1,y1 - x2,y2) */
3
4 #define ZERO(x) x < tolerance && x > -tolerance
5 #define TOLERANCE 1.0e-10
6 static double tolerance = TOLERANCE;
7
9 {
10  if (t <= 0.0)
11  t = TOLERANCE;
12  tolerance = t;
13
14  return 0;
15 }
16
17 double G_distance2_point_to_line(double x, double y, /* point */
18  double x1, double y1, double x2, double y2)
19 { /* line segment */
20  double dx, dy, t;
21
22  dx = x2 - x1;
23  dy = y2 - y1;
24
25  if (ZERO(dx) && ZERO(dy)) { /* line is degenerate */
26  dx = x1 - x;
27  dy = y1 - y;
28  return dx * dx + dy * dy; /* compute distance x,y to x1,y1 */
29  }
30
31  t = (dx * (x - x1) + dy * (y - y1)) / (dx * dx + dy * dy);
32
33  if (t < 0.0) { /* go to x1,y1 */
34  dx = x - x1;
35  dy = y - y1;
36  }
37  else if (t > 1.0) { /* go to x2,y2 */
38  dx = x - x2;
39  dy = y - y2;
40  }
41  else { /* go t from x1,y1 towards x2,y2 */
42
43  dx = x - (dx * t + x1);
44  dy = y - (dy * t + y1);
45  }
46  return dx * dx + dy * dy;
47 }
int y
Definition: plot.c:34
#define TOLERANCE
Definition: gis/line_dist.c:5
int G_set_distance_to_line_tolerance(double t)
Definition: gis/line_dist.c:8
double G_distance2_point_to_line(double x, double y, double x1, double y1, double x2, double y2)
Definition: gis/line_dist.c:17
#define ZERO(x)
Definition: gis/line_dist.c:4