line_dist.c

Go to the documentation of this file.
00001 #include <grass/gis.h>
00002 /* compute square of distance of point (x,y) to line segment (x1,y1 - x2,y2) */
00003 
00004 #define ZERO(x) x < tolerance && x > -tolerance
00005 #define TOLERANCE 1.0e-10
00006 static double tolerance = TOLERANCE;
00007 
00008 int G_set_distance_to_line_tolerance (double t)
00009 {
00010     if (t <= 0.0)
00011         t = TOLERANCE;
00012     tolerance = t;
00013 
00014     return 0;
00015 }
00016 
00017 double G_distance2_point_to_line (
00018     double x,double y,         /* point */
00019     double x1,double y1,double x2,double y2)    /* line segment */
00020 {
00021     double dx,dy,t;
00022 
00023     dx = x2 - x1;
00024     dy = y2 - y1;
00025 
00026     if (ZERO(dx) && ZERO(dy)) /* line is degenerate */
00027     {
00028         dx = x1 - x;
00029         dy = y1 - y;
00030         return dx*dx + dy*dy;   /* compute distance x,y to x1,y1 */
00031     }
00032 
00033     t = (dx * (x - x1) + dy * (y - y1)) / (dx * dx + dy * dy);
00034 
00035     if (t < 0.0)                /* go to x1,y1 */
00036     {
00037         dx = x - x1;
00038         dy = y - y1;
00039     }
00040     else if (t > 1.0)           /* go to x2,y2 */
00041     {
00042         dx = x - x2;
00043         dy = y - y2;
00044     }
00045     else                        /* go t from x1,y1 towards x2,y2 */
00046     {
00047         dx = x - (dx * t + x1);
00048         dy = y - (dy * t + y1);
00049     }
00050     return dx*dx + dy*dy;
00051 }

Generated on Wed Dec 19 14:59:06 2007 for GRASS by  doxygen 1.5.4