collision.cl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. typedef struct __attribute__ ((packed)) _Vec3 {
  2. float x, y, z;
  3. } Vec3;
  4. typedef struct __attribute__ ((packed)) _Index3 {
  5. int x, y ,z;
  6. } Index3;
  7. typedef struct __attribute__ ((packed)) _Ray {
  8. Vec3 o, d;
  9. } Ray;
  10. Vec3 my_diff(Vec3 a, Vec3 b) {
  11. Vec3 c;
  12. c.x = a.x - b.x;
  13. c.y = a.y - b.y;
  14. c.z = a.z - b.z;
  15. return c;
  16. }
  17. Vec3 my_cross(Vec3 a, Vec3 b) {
  18. Vec3 c;
  19. c.x = (a.y * b.z) - (a.z * b.y);
  20. c.y = (a.z * b.x) - (a.x * b.z);
  21. c.z = (a.x * b.y) - (a.y * b.x);
  22. return c;
  23. }
  24. float my_dot(Vec3 a, Vec3 b) {
  25. return ((a.x * b.x) + (a.y * b.y) + (a.z * b.z));
  26. }
  27. __kernel void collision(__global Ray *rays, __global Vec3 *points, __global Index3 *triangles, __global int *collisions) {
  28. const float EPSILON = 0.0000001;
  29. int i = get_global_id(0);
  30. Vec3 tv0, tv1, tv2;
  31. float a, f, u, v, x;
  32. Vec3 e1, e2, h, s, q;
  33. for (int t = 0; t < 1; t++) {
  34. tv0 = points[triangles[t].x];
  35. tv1 = points[triangles[t].y];
  36. tv2 = points[triangles[t].z];
  37. // edge detection
  38. e1 = my_diff(tv1, tv0);
  39. e2 = my_diff(tv2, tv0);
  40. // my_cross product
  41. h = my_cross(rays[i].d, e2);
  42. // my_dot product
  43. a = my_dot(e1, h);
  44. // DIVERGENCE DETECTED!
  45. if (a > -EPSILON && a < EPSILON) {
  46. collisions[i] = -5;
  47. return;
  48. }
  49. f = 1/a;
  50. s = my_diff(rays[i].o, tv0);
  51. u = f * my_dot(s, h);
  52. if (u < 0.0 || u > 1.0) {
  53. collisions[i] = -2;
  54. return;
  55. }
  56. q = my_cross(s, e1);
  57. v = f * my_dot(rays[i].d, q);
  58. if (v < 0.0 || (u + v) > 1.0) {
  59. collisions[i] = -3;
  60. return;
  61. }
  62. x = f * my_dot(e2, q);
  63. if (x > EPSILON) {
  64. collisions[i] = t;
  65. return;
  66. }
  67. collisions[i] = -4;
  68. }
  69. }