1 /* gEDA - GPL Electronic Design Automation
2 * libgeda - gEDA's library
3 * Copyright (C) 1998-2010 Ales Hvezda
4 * Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details)
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA
21 /*! \file m_geometry.c
23 * \brief Low-level mathmatical functions for lines
30 #include "libgeda_priv.h"
32 #ifdef HAVE_LIBDMALLOC
37 /*! \brief Calculates the distance between the given point and the closest
38 * point on the given line segment.
40 * If the closest point on the line resides beyond the line segment's
41 * end point, this function returns the distance from the given point to the
44 * If the line represents a single point (the endpoints are the same), this
45 * function calcualtes the distance to that point.
47 * \param [in] line The LINE object.
48 * \param [in] x The x coordinate of the given point.
49 * \param [in] y The y coordinate of the given point.
50 * \return The shortest distance from the object to the point. With an
51 * invalid parameter, this function returns G_MAXDOUBLE.
53 double m_line_shortest_distance (LINE
*line
, int x
, int y
)
62 g_return_val_if_fail (line
!= NULL
, G_MAXDOUBLE
);
64 lx0
= (double)line
->x
[0];
65 ly0
= (double)line
->y
[0];
66 ldx
= (double)(line
->x
[1] - line
->x
[0]);
67 ldy
= (double)(line
->y
[1] - line
->y
[0]);
69 if (ldx
== 0 && ldy
== 0) {
70 /* if line is a point, just calculate distance to the point */
75 /* calculate parametric value of perpendicular intersection */
76 dx0
= ldx
* (x
- lx0
);
77 dy0
= ldy
* (y
- ly0
);
79 t
= (dx0
+ dy0
) / (ldx
* ldx
+ ldy
* ldy
);
81 /* constrain the parametric value to a point on the line */
85 /* calculate closest point on the line */
89 /* calculate distance to closest point */
94 return sqrt ((dx
* dx
) + (dy
* dy
));