使用CGAL获取多边形交叉线

时间:2017-08-02 15:43:57

标签: c++ polygon cgal

如何使用CGAL轻松检索两个相交多边形的交叉线(从第一个到最后一个交叉点)。请参阅图片以获得澄清,绿线是我想要的。

Two intersecting polygons with intersection line

目前我使用以下算法,在此算法中,我得到交点多边形,然后找到两个多边形边界上的点,这些点应该是交点。这是代码:

Polygon_2 P,Q;
Pwh_list_2                  intR;
Pwh_list_2::const_iterator  it;
CGAL::intersection(P, Q, std::back_inserter(intR));

//Loop through intersection polygons
for (it = intR.begin(); it != intR.end(); ++it) {
    boost::numeric::ublas::vector<double> firstIntersectPoint(3), lastIntersectPoint(3);
    Polygon_2 Overlap = it->outer_boundary();
    typename CGAL::Polygon_2<Kernel>::Vertex_iterator vit;
    int pointNr = 1;

    //Loop through points of intersection polygon to find first and last intersection point.
    for (vit = Overlap.vertices_begin(); vit != Overlap.vertices_end(); ++vit) {
        CGAL::Bounded_side bsideThis = P.bounded_side(*vit);
        CGAL::Bounded_side bsideArg = Q.bounded_side(*vit);
        if (bsideThis == CGAL::ON_BOUNDARY && bsideArg == CGAL::ON_BOUNDARY && pointNr == 1) {
            firstIntersectPoint <<= 0, CGAL::to_double(vit->x()), CGAL::to_double(vit->y());
            pointNr = 2;
        }
        else if (bsideThis == CGAL::ON_BOUNDARY && bsideArg == CGAL::ON_BOUNDARY && pointNr == 2) {
            lastIntersectPoint <<= 0, CGAL::to_double(vit->x()), CGAL::to_double(vit->y());
            pointNr = 2;
        }
    }

    //RESULT
    std::cout << firstIntersectPoint << std::endl;
    std::cout << lastIntersectPoint << std::endl;
}

虽然这有效,但我认为这不是正确的方法。有人可以告诉我这是否是正确的方法,或者指出如何做得更好。

1 个答案:

答案 0 :(得分:2)

将两个多边形的片段插入2D排列。然后找到度数为4的顶点。请注意,在一般情况下可能有2个以上;可能没有,可能有1个。

std::list<X_monotone_curve_2> segments;
for (const auto& pgn : polygons) {
  for (auto it = pgn.curves_begin(); it != pgn.curves_end(); ++it)
    segments.push_back(*it);
}
Arrangement_2 arr;
insert(arr, segments.begin(), segments.end());
for (auto it = arr.begin_vertices(); it != arr.end_vertices(); ++it) {
  if (4 == it->degree())
  ...
}

您可以避免构建“segment”列表,而是使用迭代器适配器直接将多边形的片段插入到排列中。 (这是纯粹的通用编程,与CGAL无关。)