将多边形坐标从Double转换为Long以用于Clipper库

Converting polygon coordinates from Double to Long for use with Clipper library

本文关键字:Long 用于 Clipper 转换 多边形 坐标 Double      更新时间:2023-10-16

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

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

我不知道该怎么做。

您可以使用一个简单的乘法器在两者之间进行转换:

/* 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。