Created
September 19, 2018 11:49
-
-
Save w8r/f1b2c88a439c448257d075d62dd18fe5 to your computer and use it in GitHub Desktop.
Point in polygon by winding number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isLeft (x0, y0, x1, y1, x2, y2) { | |
return ((x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)); | |
} | |
export default function pointInPoygon (x, y, V) { | |
let wn = 0; // winding number | |
for (let i = 0; i < V.length - 1; i++) { // edge from V[i] to V[i+1] | |
const vi = V[i], vj = V[i + 1]; | |
if (vi.y <= y) { // start y <= P.y | |
if (vj.y > y) { // an upward crossing | |
//if ((vj.x - vi.x) * (y - vi.y) - (x - vi.x) * (vj.y - vi.y) > 0) { | |
if (isLeft(vi.x, vi.y, vj.x, vj.y, x, y) > 0) { // P left of edge | |
++wn; // have a valid up intersect | |
} | |
} | |
} else { // start vy > y (no test needed) | |
if (vj.y <= y) { // a downward crossing | |
// if ((vj.x - vi.x) * (y - vi.y) - (x - vi.x) * (vj.y - vi.y) < 0) { | |
if (isLeft(vi.x, vi.y, vj.x, vj.y, x, y) < 0) { // P right of edge | |
--wn; // have a valid down intersect | |
} | |
} | |
} | |
} | |
return wn !== 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment