Lua: Point in polygon function

Sgraffite

Supreme [H]ardness
Joined
Jan 10, 2006
Messages
4,405
I'm having trouble getting this point in polygon function to work correctly in lua. I converted it from this C code from this site:
Code:
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
	 (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

To this lua code:

Code:
function pnpoly( vertx, verty, testx, testy )
    nvert = table.getn(vertx);
    c = -1;
    j = nvert - 1;
    for i = 1, nvert do
        if ( ((verty[i] > testy) ~= (verty[j] > testy)) and (testx < (vertx[j] - vertx[i]) * (testy - verty[i]) / (verty[j] - verty[i]) + vertx[i]) ) then
            c = c * -1;
        end
        j = i;
    end
    return c;
end

I was testing it on a 4 sided polygon, and it works sometimes, but there are spots in the polygon where it should register as being inside but does not. I was reading about this issue and it appears that that problem is associated with variables being passed as integers and not floating points. But after further reading it seems lua should have any issues with this happening.

The best example I could find to what is happening is this picture:
integer_polygon_problem.gif


Where my defined region is the blue, but when testing if I am inside the polygon only the red part shows true.

Any ideas as to why this would be happening?
 
Back
Top