Ray_Tracing.pde 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Triangle
  2. class Triangle {
  3. // position
  4. PVector p1, p2, p3;
  5. // color
  6. color c1, c2, c3;
  7. BoundingBox bbx;
  8. Triangle(PVector p1, PVector p2, PVector p3, color c1, color c2, color c3) {
  9. this.p1 = p1;
  10. this.p2 = p2;
  11. this.p3 = p3;
  12. this.c1 = c1;
  13. this.c2 = c2;
  14. this.c3 = c3;
  15. bbx = new BoundingBox();
  16. bbx.create(this);
  17. }
  18. // check to see if a ray intersects with the triangle
  19. boolean intersect(Ray r, float[] param) {
  20. PVector p21 = PVector.sub(p2, p1);
  21. PVector p31 = PVector.sub(p3, p1);
  22. PVector po1 = PVector.sub(r.ori, p1);
  23. PVector dxp31 = r.dir.cross(p31);
  24. PVector po1xp21 = po1.cross(p21);
  25. float denom = p21.dot(dxp31);
  26. float t = p31.dot(po1xp21) / denom;
  27. float alpha = po1.dot(dxp31) / denom;
  28. float beta = r.dir.dot(po1xp21) / denom;
  29. boolean res = t > 0 && alpha > 0 && alpha < 1 && beta > 0 && beta < 1 &&
  30. alpha + beta < 1;
  31. // depth test
  32. if (res && t < param[0]) {
  33. param[0] = t;
  34. param[1] = alpha * p1.x + beta * p2.x + (1 - alpha - beta) * p3.x;
  35. param[2] = alpha * p1.y + beta * p2.y + (1 - alpha - beta) * p3.y;
  36. param[3] = alpha * p1.z + beta * p2.z + (1 - alpha - beta) * p3.z;
  37. }
  38. return res;
  39. }
  40. void render() {
  41. beginShape(TRIANGLES);
  42. fill(c1);
  43. vertex(p1.x, p1.y, p1.z);
  44. fill(c2);
  45. vertex(p2.x, p2.y, p2.z);
  46. fill(c3);
  47. vertex(p3.x, p3.y, p3.z);
  48. endShape();
  49. }
  50. }
  51. // Ray
  52. class Ray {
  53. // origin and direction
  54. PVector ori, dir;
  55. Ray(PVector ori, PVector dir) {
  56. this.ori = ori;
  57. this.dir = dir;
  58. }
  59. }