00001 /* 00002 * Copyright 2000, Brown University, Providence, RI. 00003 * 00004 * All Rights Reserved 00005 * 00006 * Permission to use, copy, modify, and distribute this software and its 00007 * documentation for any purpose other than its incorporation into a 00008 * commercial product is hereby granted without fee, provided that the 00009 * above copyright notice appear in all copies and that both that 00010 * copyright notice and this permission notice appear in supporting 00011 * documentation, and that the name of Brown University not be used in 00012 * advertising or publicity pertaining to distribution of the software 00013 * without specific, written prior permission. 00014 * 00015 * BROWN UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, 00016 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ANY 00017 * PARTICULAR PURPOSE. IN NO EVENT SHALL BROWN UNIVERSITY BE LIABLE FOR 00018 * ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 00019 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 00020 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 00021 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 00022 */ 00023 #ifndef _MLIB_NEAREST_PT_TO_LINE_SEG 00024 #define _MLIB_NEAREST_PT_TO_LINE_SEG 00025 00026 // returns the nearest point on the line defined by (st,en) to the 00027 // point, pt. 00028 // 00029 template <class P> 00030 inline P nearest_pt_to_line(const P &pt, const P &st, const P &en) { 00031 return st + (en-st)*((en-st)*(pt-st)/(en-st).lengthSqrd()); 00032 } 00033 00034 // returns the nearest point on the line segment (st,en) to the 00035 // point, pt. 00036 // 00037 template <class P> 00038 inline P nearest_pt_to_line_seg(const P &pt, const P &st, const P &en) { 00039 P npt = nearest_pt_to_line(pt, st, en); 00040 if ((npt - st) * (npt - en) < 0) 00041 return npt; 00042 return ((pt-st).lengthSqrd()<(pt-en).lengthSqrd()) ? st : en; 00043 } 00044 00045 #endif