core/vgl/vgl_polygon_test.txx
Go to the documentation of this file.
00001 // This is core/vgl/vgl_polygon_test.txx
00002 #ifndef vgl_polygon_test_txx_
00003 #define vgl_polygon_test_txx_
00004 //:
00005 // \file
00006 // \author fsm
00007 
00008 #include "vgl_polygon_test.h"
00009 #include <vgl/vgl_lineseg_test.h>
00010 
00011 template <class T>
00012 bool vgl_polygon_test_inside(T const *xs, T const *ys, unsigned n, T x, T y)
00013 {
00014   // compute centre
00015   T cx = 0;
00016   T cy = 0;
00017   for (unsigned i=0; i<n; ++i) {
00018     cx += xs[i];
00019     cy += ys[i];
00020   }
00021   cx /= n;
00022   cy /= n;
00023 
00024   // compute a point outside the polygon.
00025   T ox = 0, oy = 0;
00026   for (unsigned i=0; i<n; ++i) {
00027     T tmp;
00028 
00029     tmp = xs[i]-cx;
00030     if (tmp<0) tmp = -tmp;
00031     if (tmp>ox) ox = tmp;
00032 
00033     tmp = ys[i]-cy;
00034     if (tmp<0) tmp = -tmp;
00035     if (tmp>oy) oy = tmp;
00036   }
00037   ox = cx + ox + oy + 1;
00038   oy = cy + ox + oy + 1;
00039 
00040   // count crossings.
00041   unsigned crossings = 0;
00042   for (unsigned i=0; i<n; ++i)
00043     if (vgl_lineseg_test_lineseg(xs[i], ys[i], xs[(i+1)%n], ys[(i+1)%n],   ox, oy, x, y))
00044       ++crossings;
00045 
00046   // inside iff there was an odd number of crossings.
00047   return crossings % 2 != 0;
00048 }
00049 
00050 //--------------------------------------------------------------------------------
00051 
00052 #undef VGL_POLYGON_TEST_INSTANTIATE
00053 #define VGL_POLYGON_TEST_INSTANTIATE(T) \
00054 template bool vgl_polygon_test_inside(T const*, T const*, unsigned, T, T)
00055 
00056 #endif // vgl_polygon_test_txx_