rowanwins/point-in-polygon-hao

Winding order causes edge intersections to fail

BlueWater86 opened this issue · 5 comments

   const square = [
        [0, 0],
        [0, 1],
        [1, 1],
        [1, 0],
        [0, 0]
    ]
    const squareWithFlippedWinding = [
        [0, 0],
        [1, 1],
        [0, 1],
        [1, 0],
        [0, 0]
    ]
    const verticalEdgePoint = [0, 0.5]
    const horizontalEdgePoint = [0.5, 0]

    console.assert(inside(verticalEdgePoint, [square]) === 0, "Vertical edge point")
    console.assert(inside(horizontalEdgePoint, [square]) === 0, "Horizontal edge point")
    console.assert(inside(verticalEdgePoint, [squareWithFlippedWinding]) === 0, "Vertical edge point, flipped winding order")

Thanks for the interesting test case @BlueWater86 - the original paper that this algorithm came from said that winding order was not a factor.
It seems that the horizontal edge point works on flipped winding polygon, so it's just the vertical point that seems problematic...
I haven't been able to find a reference implementation to compare results against so it probably requires some digging

I went backwards through the algorithm to find this edge case and I'm pretty sure that by introducing more sides to the polygon many more edge intersections will fail due to winding order.

I'm now living with the fact that an upstream library should have already sorted points before performing a point in polygon calculation.

@BlueWater86 I've just taken a closer look at your case, your squareWithFlippedWinding is actually incorrect in the sequence of coordinates.
It should be

const squareWithFlippedWinding = [[
    [0, 0],
    [1, 0],
    [1, 1],
    [0, 1],
    [0, 0]
]]

With the correct sequence it returns the right result.

Sorry for the silly mistake