Boost.Geometry 閉じないポリゴン

boost::geometry::model::polygonはデフォルトで、ポリゴンが閉じていなければなりません(first == last。(0, 0)で始まったら(0, 0)で終わらないといけない)。


そのため、閉じていないポリゴンを操作するアルゴリズムは、おかしな結果を返すことがあります:

#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/assign/list_of.hpp>

namespace bg = boost::geometry;

typedef bg::model::d2::point_xy<double> point;
typedef bg::model::polygon<point> polygon;

int main()
{
    polygon poly;
    bg::exterior_ring(poly) = boost::assign::list_of<point>
        (0, 0)
        (3, 3)
        (3, 0)
//      (0, 0) // 閉じない
        ;

    const double result = bg::area(poly); // 面積を計算する

    std::cout << result << std::endl;
}
0


boost::geometry::model::polygonは、第3テンプレート引数Closedをfalseに設定することで、閉じないポリゴンを許容します。これを設定すると、閉じていないポリゴンでもアルゴリズムが正しく動作します。

#include <iostream>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/assign/list_of.hpp>

namespace bg = boost::geometry;

typedef bg::model::d2::point_xy<double> point;

static const bool clock_wise = true;
static const bool closed = false; // 閉じないことを許可するポリゴンにする
typedef bg::model::polygon<point, clock_wise, closed> polygon;

int main()
{
    polygon poly;
    bg::exterior_ring(poly) = boost::assign::list_of<point>
        (0, 0)
        (3, 3)
        (3, 0)
        ;

    const double result = bg::area(poly); // 面積を計算する

    std::cout << result << std::endl;
}
4.5