1

I have some code converted over to python from C++ :

def diff(a,b):
    r=[None,None,None];
    r[0] = a[0]-b[0];
    r[1] = a[1]-b[1];
    r[2] = a[2]-b[2];
    return r;

def cross(a,b):
    r=[None,None,None];
    r[0] = a[1] * b[2] - a[2] * b[1];
    r[1] = a[2] * b[0] - a[0] * b[2];
    r[2] = a[0] * b[1] - a[1] * b[0];
    return r;

def dot(a,b):
  return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];    
  
def point_over_triangle(a ,b ,c ,p):
    ba = cb = ac = px = n = nx = [None,None,None];
    
    ba = diff(b, a);
    cb = diff(c, b);
    ac = diff(a, c);    
    
    n = cross(ac, ba);  # Same as n = ba X ca
    
    px = diff(p, a);
    nx = cross(ba, px);
    if (dot(nx, n) < 0):
        return 0;

    px = diff(p, b);
    nx = cross(cb, px);
    if (dot(nx, n) < 0):
        return 0;

    px = diff(p, c);
    nx = cross(ac, px);
    if (dot(nx, n) < 0):
        return 0;
    
    return 1;
def convert(ListedVar):
    ListedVar[0]=float(ListedVar[0]);
    ListedVar[1]=float(ListedVar[1]);    
    ListedVar[2]=float(ListedVar[2]);
    return ListedVar;
#Defaults
a = [ 1, 1, 0 ];
b = [ 0, 1, 1 ];
c = [ 1, 0, 1 ];
p = [ 0, 0, 0 ];

print("Please enter your triangle coordinates:");
a = input("point 1:").split(',');
a = convert(a);
b = input("point 2:").split(',');
b = convert(b);
c = input("point 3:").split(',');
c = convert(c);

#Point to check for.
print("And the point you want to check if is or is not in the triangle:");
p = input("point CONTACT:").split(',');
p = convert(p);

if point_over_triangle(a, b, c, p) > 0:
    print("over");
else:
    print("not over");

The problem with it is that it can return extremely spurious results, such as thinking that 0,0,0 is in the triangle:

0,1,1

1,0,1

1,1,0

(which it isn't)

I've looked at some others as well and none of them ever seem to return the results they are supposed to. So I'm curious what is the pythonic way of doing this that has the fewest number of faulty outliers. [aka thinking it's in the triangle when it's not or thinking it's not in the triangle when it is].

Frederick
  • 47
  • 10

0 Answers0