#include "Triangle.h"

double determinant(Vector v0, Vector v1, Vector v2) {
    double ret = 0;
    ret += v0[0]*v1[1]*v2[2];
    ret += v1[0]*v2[1]*v0[2];
    ret += v2[0]*v0[1]*v1[2];

    ret -= v2[0]*v1[1]*v0[2];
    ret -= v0[0]*v2[1]*v1[2];
    ret -= v1[0]*v0[1]*v2[2];

    if(ret==0) cerr << "zero determinant\n", exit(1);

    return ret;
}


bool Triangle::intersected(Ray& ray) {
    //solve the intersection through a 3X3 linear equations.
    //these are the four coloum vectors
    Vector Alpha = V1-V0;
    Vector Beta = V2-V0;
    Vector T = - ray.GetDirection();
    Vector Rhs = ray.GetOrigin() - V0;

    //the determinants and solutions if necessary
    double D = determinant(Alpha, Beta, T);

    double D1 = determinant(Rhs, Beta, T), alpha = D1/D;
    if(alpha>1-EPSILON || alpha < EPSILON) return false;

    double D2 = determinant(Alpha, Rhs, T), beta = D2/D;
    if(beta>1-EPSILON || beta < EPSILON) return false;
    if(alpha+beta > 1-EPSILON) return false;

    double D3 = determinant(Alpha, Beta, Rhs);
    ray.Parameter() = D3/D;
    return true;
}


