libgeda

m_line.c

Go to the documentation of this file.
00001 /* gEDA - GPL Electronic Design Automation
00002  * libgeda - gEDA's library
00003  * Copyright (C) 1998-2010 Ales Hvezda
00004  * Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details)
00005  *
00006  * This program is free software; you can redistribute it and/or modify
00007  * it under the terms of the GNU General Public License as published by
00008  * the Free Software Foundation; either version 2 of the License, or
00009  * (at your option) any later version.
00010  *
00011  * This program is distributed in the hope that it will be useful,
00012  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00013  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00014  * GNU General Public License for more details.
00015  *
00016  * You should have received a copy of the GNU General Public License
00017  * along with this program; if not, write to the Free Software
00018  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00019  */
00020 
00026 #include <config.h>
00027 #include <math.h>
00028 #include <stdio.h>
00029 
00030 #include "libgeda_priv.h"
00031 
00032 #ifdef HAVE_LIBDMALLOC
00033 #include <dmalloc.h>
00034 #endif
00035 
00036 
00053 double m_line_shortest_distance (LINE *line, int x, int y)
00054 {
00055   double cx, cy;
00056   double dx, dy;
00057   double dx0, dy0;
00058   double lx0, ly0;
00059   double ldx, ldy;
00060   double t;
00061 
00062   g_return_val_if_fail (line != NULL, G_MAXDOUBLE);
00063 
00064   lx0 = (double)line->x[0];
00065   ly0 = (double)line->y[0];
00066   ldx = (double)(line->x[1] - line->x[0]);
00067   ldy = (double)(line->y[1] - line->y[0]);
00068 
00069   if (ldx == 0 && ldy == 0) {
00070     /* if line is a point, just calculate distance to the point */
00071     dx = x - lx0;
00072     dy = y - ly0;
00073 
00074   } else {
00075     /* calculate parametric value of perpendicular intersection */
00076     dx0 = ldx * (x - lx0);
00077     dy0 = ldy * (y - ly0);
00078 
00079     t = (dx0 + dy0) / (ldx * ldx + ldy * ldy);
00080 
00081     /* constrain the parametric value to a point on the line */
00082     t = max (t, 0);
00083     t = min (t, 1);
00084 
00085     /* calculate closest point on the line */
00086     cx = t * ldx + lx0;
00087     cy = t * ldy + ly0;
00088 
00089     /* calculate distance to closest point */
00090     dx = x - cx;
00091     dy = y - cy;
00092   }
00093 
00094   return sqrt ((dx * dx) + (dy * dy));
00095 }
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Defines