# liblayout / polygon.cpp

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109``` ```/* ** This code is distributed under a modified BSD license. ** Please refer to http://www.sourceforge.net/projects/adsm/ ** ************************************************************************* ** ** Copyright (c) 2004-2006 Robert W. Johnstone ** All rights reserved. ** ************************************************************************* ** ** Description not written. ** */ #include "layout.h" #include #include using namespace liblayout; rect polygon::bounds() const { if ( empty() ) throw std::runtime_error( "Polygon is empty." ); const_iterator lp = begin(); rect r( lp->x, lp->y, lp->x, lp->y ); for ( ++lp; lp != end(); ++lp ) { r += *lp; } return r; } void polygon::normalize() { // nothing to do if the polygon is empty if ( begin() == end() ) return; // first check against front and back // this test needs to be done, and it is cheapest to // pop_back to remove duplicates while( size()>1 && front() == back() ) pop_back(); assert( begin() != end() ); // remember, the first point is always unique const_iterator lp = begin() + 1; iterator out = begin()+1; for ( ; lp != end(); ++lp ) { if ( *lp != *(lp-1) ) { *out = *lp; ++out; } } // we don't need anything in the array [out,end) erase( out, end() ); } bool polygon::valid() const { // first, we need at least three points if ( size()<3 ) return false; // check for distinct x and distinct y values const_iterator lp = begin(); rect r( lp->x, lp->y, lp->x, lp->y ); for ( ++lp; lp != end(); ++lp ) { r += *lp; if ( r.valid() ) return true; } return false; } #ifdef TEST_MODULE using liblayout::point; using liblayout::polygon; static void test1() { polygon p; p.push_back( point(0,0) ); assert( !p.valid() ); p.push_back( point(0,1) ); assert( !p.valid() ); p.push_back( point(1,1) ); assert( p.valid() ); } static void test2() { polygon p; p.push_back( point(0,0) ); assert( !p.valid() ); p.push_back( point(0,1) ); assert( !p.valid() ); p.push_back( point(0,2) ); assert( !p.valid() ); p.push_back( point(1,1) ); assert( p.valid() ); } int main(int argc, char* argv[]) { test1(); test2(); } #endif ```