vgl_polygon_test.hxx
Go to the documentation of this file.
1 // This is core/vgl/vgl_polygon_test.hxx
2 #ifndef vgl_polygon_test_hxx_
3 #define vgl_polygon_test_hxx_
4 //:
5 // \file
6 // \author fsm
7 
8 #include "vgl_polygon_test.h"
9 #include <vgl/vgl_lineseg_test.h>
10 
11 template <class T>
12 bool vgl_polygon_test_inside(T const *xs, T const *ys, unsigned n, T x, T y)
13 {
14  // compute centre
15  T cx = 0;
16  T cy = 0;
17  for (unsigned i=0; i<n; ++i) {
18  cx += xs[i];
19  cy += ys[i];
20  }
21  cx /= n;
22  cy /= n;
23 
24  // compute a point outside the polygon.
25  T ox = 0, oy = 0;
26  for (unsigned i=0; i<n; ++i) {
27  T tmp;
28 
29  tmp = xs[i]-cx;
30  if (tmp<0) tmp = -tmp;
31  if (tmp>ox) ox = tmp;
32 
33  tmp = ys[i]-cy;
34  if (tmp<0) tmp = -tmp;
35  if (tmp>oy) oy = tmp;
36  }
37  ox = cx + ox + oy + 1;
38  oy = cy + ox + oy + 1;
39 
40  // count crossings.
41  unsigned crossings = 0;
42  for (unsigned i=0; i<n; ++i)
43  if (vgl_lineseg_test_lineseg(xs[i], ys[i], xs[(i+1)%n], ys[(i+1)%n], ox, oy, x, y))
44  ++crossings;
45 
46  // inside iff there was an odd number of crossings.
47  return crossings % 2 != 0;
48 }
49 
50 //--------------------------------------------------------------------------------
51 
52 #undef VGL_POLYGON_TEST_INSTANTIATE
53 #define VGL_POLYGON_TEST_INSTANTIATE(T) \
54 template bool vgl_polygon_test_inside(T const*, T const*, unsigned, T, T)
55 
56 #endif // vgl_polygon_test_hxx_
bool vgl_lineseg_test_lineseg(vgl_line_segment_2d< T > const &l1, vgl_line_segment_2d< T > const &l2)
return true if the two linesegments meet.
bool vgl_polygon_test_inside(T const *xs, T const *ys, unsigned n, T x, T y)
return true iff (x, y) is inside (or on boundary of) the given n-gon.