Ask CSDN
The following is a simple code for intersecting rays and triangles in ray tracing, using C++ language and OpenGL library.
First, we need to define a ray class (Ray), including the origin (origin) and direction vector (direction):
copyclass Ray {
public:
vec3 origin;
vec3 direction;
Ray(vec3 o, vec3 d) {
origin = o;
direction = d;
}
};
Next, we define a triangle class (Triangle), which contains three points (p1, p2, p3), and a method to calculate the normal vector (normal):
copyclass Triangle {
public:
vec3 p1, p2, p3;
vec3 normal;
Triangle(vec3 v1, vec3 v2, vec3 v3) {
p1 = v1;
p2 = v2;
p3 = v3;
normal = normalize(cross(p2 - p1, p3 - p1));
}
bool intersect(Ray ray, float& t) {
vec3 e1 = p2 - p1;
vec3 e2 = p3 - p1;
vec3 h = cross(ray.direction, e2);
float a = dot(e1, h);
if (a > -EPSILON && a < EPSILON) {
return false;
}
float f = 1.0 / a;
vec3 s = ray.origin - p1;
float u = f * dot(s, h);
if (u < 0.0 || u > 1.0) {
return false;
}
vec3 q = cross(s, e1);
float v = f * dot(ray.direction, q);
if (v < 0.0 || u + v > 1.0) {
return false;
}
t = f * dot(e2, q);
if (t > EPSILON) {
return true;
}
return false;
}
};
In the above code, we used the Möller–Trumbore algorithm to determine whether the ray intersects the triangle. If it intersects, the distance t from the intersection point to the ray origin is returned.
Finally, we can use the following code to perform ray tracing and find the intersection point of the ray and the triangle:
copyfloat intersect(Ray ray, Triangle triangle) {
float t;
if (triangle.intersect(ray, t)) {
return t;
}
return INFINITY;
}
vec3 trace(Ray ray) {
float tmin = INFINITY;
Triangle* hitTriangle = nullptr;
for (auto triangle : triangles) {
float t = intersect(ray, triangle);
if (t < tmin) {
tmin = t;
hitTriangle = ▵
}
}
if (hitTriangle == nullptr) {
return vec3(0, 0, 0);
}
vec3 hitPoint = ray.origin + tmin * ray.direction;
vec3 normal = hitTriangle->normal;
return normal;
}
In the above code, we first loop through all the triangles, find the closest intersection point to the ray start point, and record the triangle. If no intersection is found, it returns black (vec3(0, 0, 0)), indicating that no object was illuminated.
Then, we compute the normal vector of the intersection point and return it as the color. In this simple ray tracing scene, we only consider the diffuse reflection, so we directly use the normal vector as the color. In actual ray tracing, we need to consider multiple reflections and refractions, and need to use a more complex optical model to calculate the color.
Moller Trumbore Algorithm
The mixed product, combining the calculation results of the determinant with the volume of the parallelepiped, is easy to understand.
result
The derivation process
a Chinese
There are 3 conditions mentioned in it.