title: Intersection between line and triangle in 3D
body: <p>I have a line and a triangle somewhere in 3D space. In other words, I have 3 points ([x,y,z] each) for the triangle, and two points (also [x,y,z]) for the line.</p>
  
  <p>I need to figure out a way, hopefully using C++, to figure out if the line ever crosses the triangle. A line parallel to the triangle, and with more than one point in common, should be counted as "does not intersect".</p>
  
  <p>I already made some code, but it doesn't work, and I always get false even when a visual representation clearly shows an intersection.</p>
  
  <pre><code>ofVec3f P1, P2;
  P1 = ray.s;
  P2 = ray.s + ray.t;
  
  ofVec3f p1, p2, p3;
  p1 = face.getVertex(0);
  p2 = face.getVertex(1);
  p3 = face.getVertex(2);
  
  ofVec3f v1 = p1 - p2;
  ofVec3f v2 = p3 - p2;
  
  float a, b, c, d;
  
  a = v1.y * v2.z - v1.z * v2.y;
  b = -(v1.x * v2.z - v1.z * v2.x);
  c = v1.x * v2.y - v1.y * v2.x;
  d = -(a * p1.x + b * p1.y + c * p1.z);
  
  ofVec3f O = P1;
  ofVec3f V = P2 - P1;
  
  float t;
  
  t = -(a * O.x + b * O.y + c * O.z + d) / (a * V.x + b * V.y + c * V.z);
  
  ofVec3f p = O + V * t;
  
  float xmin = std::min(P1.x, P2.x);
  float ymin = std::min(P1.y, P2.y);
  float zmin = std::min(P1.z, P2.z);
  
  float xmax = std::max(P1.x, P2.x);
  float ymax = std::max(P1.y, P2.y);
  float zmax = std::max(P1.z, P2.z);
  
  
  if (inside(p, xmin, xmax, ymin, ymax, zmin, zmax)) {
      *result = p.length();
      return true;
  }
  return false;
  </code></pre>
  
  <p>And here is the definition of inside()</p>
  
  <pre><code>bool primitive3d::inside(ofVec3f p, float xmin, float xmax, float ymin, float ymax, float zmin, float zmax) const {
      if (p.x &gt;= xmin &amp;&amp; p.x &lt;= xmax &amp;&amp; p.y &gt;= ymin &amp;&amp; p.y &lt;= ymax &amp;&amp; p.z &gt;= zmin &amp;&amp; p.z &lt;= zmax)
          return true;
  
      return false;
  }
  </code></pre>