8

我有两个多边形,它们的顶点存储为双坐标。我想找到这些多边形的相交区域,所以我正在查看Clipper 库(C++ 版本)。问题是,Clipper 仅适用于整数数学(它使用 Long 类型)。

有没有一种方法可以安全地用相同的比例因子转换我的两个多边形,将它们的坐标转换为 Longs,使用 Clipper 执行交叉算法,并用相同的因子将生成的交叉多边形缩小,然后将其转换回 Double没有太多的精度损失?

我无法完全理解如何做到这一点。

4

1 回答 1

7

您可以使用简单的乘数在两者之间进行转换:

/* Using power-of-two because it is exactly representable and makes
the scaling operation (not the rounding!) lossless. The value 1024
preserves roughly three decimal digits. */
double const scale = 1024.0;

// representable range
double const min_value = std::numeric_limits<long>::min() / scale;
double const max_value = std::numeric_limits<long>::max() / scale;

long
to_long(double v)
{
    if(v < 0)
    {
        if(v < min_value)
            throw out_of_range();
        return static_cast<long>(v * scale - 0.5);
    }
    else
    {
        if(v > max_value)
            throw out_of_range();
        return static_cast<long>(v * scale + 0.5);
    }
}

请注意,您制作的比例越大,您的精度就越高,但它也会降低范围。实际上,这会将浮点数转换为定点数。

最后,您应该能够使用浮点数学轻松定位代码以计算线段之间的交点,所以我想知道您为什么要完全使用 Clipper。

于 2013-07-18T05:43:29.547 回答