javascript - Triangle intersection in raytracer not working -


i trying make own raytracer in javascript. far spheres work well. want expand capabilities include triangles, , there can go squares, cubes , beyond. code have finding intersections triangles follows

function triangleintersection(t, r) { var norm = trianglenormal(t); var dist = triangledistance(t); var = vector.dotproduct(r.vector, norm);  if (a === 0) {     return -1; } else {     var b = vector.dotproduct(norm, vector.add(r.point, vector.negative(vector.multiply(norm, dist))));     var d = -1 * b / a;      var qx = vector.scale(r.vector, d).x + r.point.x;     var qy = vector.scale(r.vector, d).y + r.point.y;     var qz = vector.scale(r.vector, d).z + r.point.z;      var q = new vector(qx, qy, qz);      var ca = vector.subtract(t.points[2], t.points[0]);     var qa = vector.subtract(q, t.points[0]);     var t1 = vector.dotproduct(vector.crossproduct(ca, qa), norm);      var bc = vector.subtract(t.points[1], t.points[2]);     var qc = vector.subtract(q, t.points[2]);     var t2 = vector.dotproduct(vector.crossproduct(bc, qc), norm);      var ab = vector.subtract(t.points[0], t.points[1]);     var qb = vector.subtract(q, t.points[1]);     var t3 = vector.dotproduct(vector.crossproduct(ab, qb), norm);      if ((t1 >= 0) && (t2 >= 0) && (t3 >= 0)) {         return 1 * b / a;     } else {         return -1;     } } 

}

triangle objects have point array (points[]) , item 0 point a, item 1 point b , item 2 point c. parameter t 1 of these triangles. parameter r ray object, properties point origin, , vector, direction.

i have these functions finding normal , distance of triangle.

function trianglenormal(s) { var ca = vector.subtract(s.points[2], s.points[0]); var ba = vector.subtract(s.points[1], s.points[0]); var norm = vector.unitvector(vector.crossproduct(ca, ba));  return norm; }  function triangledistance(t) {     return vector.dotproduct(trianglenormal(t, 0), t.points[0]); } 

when render scene triangle use in scene red colored. no matter how far move camera triangle fills whole scene red. not know why happens.

an important error in plane intersection code comparison operation:

a === 0

there 2 things wrong it:

  1. for ray tracing want ray hit planes in front of source, not behind it, need a < 0.

  2. even if did want ray hit planes behind it, must never equality operations between floating point values, because floating point calculations not exact. (you must abs(a) < 1e-6f or small value)


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -