Arty
intersect.h
1 #ifndef INTERSECT_H
2 #define INTERSECT_H
3 
4 #include <cfloat>
5 #include <cstdint>
6 
7 #include "float4.h"
8 #include "float3.h"
9 
11 struct Ray {
13  float tmin;
15  float tmax;
16 
17  Ray()
18  : org(0.0f), tmin(0.0f), dir(0.0f), tmax(0.0f)
19  {}
20 
21  Ray(const float3& o, const float3& d,
22  float t0 = 0.0f, float t1 = FLT_MAX)
23  : org(o), tmin(t0), dir(d), tmax(t1)
24  {}
25 };
26 
28 struct Hit {
29  int32_t tri;
30  float t;
31  float u;
32  float v;
33 
34  Hit()
35  : tri(-1), t(0.0f), u(0.0f), v(0.0f)
36  {}
37 
38  Hit(int32_t tri, float t, float u, float v)
39  : tri(tri), t(t), u(u), v(v)
40  {}
41 };
42 
45  float3 v0; float nx;
46  float3 e1; float ny;
47  float3 e2; float nz;
48 
49  PrecomputedTri() {}
50  PrecomputedTri(const float3& v0, const float3& v1, const float3& v2)
51  : v0(v0), e1(v0 - v1), e2(v2 - v0)
52  {
53  auto n = cross(e1, e2);
54  nx = n.x;
55  ny = n.y;
56  nz = n.z;
57  }
58 };
59 
61 inline bool intersect_ray_tri(const Ray& ray, const PrecomputedTri& tri, float& t, float& u, float& v) {
62  const float eps = 1e-9f;
63  float3 n(tri.nx, tri.ny, tri.nz);
64 
65  auto c = tri.v0 - ray.org;
66  auto r = cross(ray.dir, c);
67  auto det = dot(n, ray.dir);
68  auto abs_det = std::fabs(det);
69 
70  auto u_ = prodsign(dot(r, tri.e2), det);
71  auto v_ = prodsign(dot(r, tri.e1), det);
72  auto w_ = abs_det - u_ - v_;
73 
74  if (u_ >= -eps && v_ >= -eps && w_ >= -eps) {
75  auto t_ = prodsign(dot(n, c), det);
76  if (t_ >= abs_det * ray.tmin && abs_det * t > t_) {
77  auto inv_det = 1.0f / abs_det;
78  t = t_ * inv_det;
79  u = u_ * inv_det;
80  v = v_ * inv_det;
81  return true;
82  }
83  }
84 
85  return false;
86 }
87 
88 #endif // INTERSECT_H
float3 org
Origin of the ray.
Definition: intersect.h:12
Definition: float3.h:10
float3 dir
Direction of the ray.
Definition: intersect.h:14
float tmin
Minimum t parameter.
Definition: intersect.h:13
int32_t tri
Triangle index, or -1 if no intersection was found.
Definition: intersect.h:29
float t
Time of intersection.
Definition: intersect.h:30
float u
First barycentric coordinate.
Definition: intersect.h:31
Ray-triangle hit information.
Definition: intersect.h:28
float v
Second barycentric coordinate.
Definition: intersect.h:32
Ray defined as org + t * dir, with t in [tmin, tmax].
Definition: intersect.h:11
float tmax
Maximum t parameter.
Definition: intersect.h:15
Precomputed triangle structure to accelerate ray-scene intersections.
Definition: intersect.h:44