在这次作业中,要实现两个部分:光线的生成和光线与三角的相交。本次代码框架的工作流程为:
需要修改的函数是:
Render()生成从人眼射向像素的射线
需要将栅格空间坐标(i, j) -> 世界坐标(x, y)
可以参考这篇文章
Ray-Tracing: Generating Camera Rays (Generating Camera Rays)
具体步骤如下
Raster space -> NDC space
NDC space -> Screen space
公式如下
调整y轴的朝向
Screen space -> World space
参考代码
for (int j = 0; j < scene.height; ++j)
{
for (int i = 0; i < scene.width; ++i)
{
// generate primary ray direction
float x;
float y;
// TODO: Find the x and y positions of the current pixel to get the direction
// vector that passes through it.
// Also, don't forget to multiply both of them with the variable *scale*, and
// x (horizontal) variable with the *imageAspectRatio*
x = (2.0f*(float(i)+0.5f)/scene.width-1.0f)*imageAspectRatio*scale;
y = (1.0f-2.0f*(float(j)+0.5f)/scene.height)*scale;
Vector3f dir = Vector3f(x, y, -1); // Don't forget to normalize this direction!
framebuffer[m++] = castRay(eye_pos, dir, scene, 0);
}
UpdateProgress(j / (float)scene.height);
}
使用Moller-Trumbore算法,判断光线与物体是否有交点,并且更新tnear, u 和 v( 对应下图中的t, b1, b2)
bool rayTriangleIntersect(const Vector3f& v0, const Vector3f& v1, const Vector3f& v2, const Vector3f& orig,
const Vector3f& dir, float& tnear, float& u, float& v)
{
// TODO: Implement this function that tests whether the triangle
// that's specified bt v0, v1 and v2 intersects with the ray (whose
// origin is *orig* and direction is *dir*)
// Also don't forget to update tnear, u and v.
Vector3f E1 = v1 - v0;
Vector3f E2 = v2 - v0;
Vector3f S = orig - v0;
Vector3f S1 = crossProduct(dir, E2);
Vector3f S2 = crossProduct(S, E1);
float k = 1.0f/dotProduct(S1, E1);
tnear = k * dotProduct(S2,E2);
u = k * dotProduct(S1,S);
v = k * dotProduct(S2,dir);
if(tnear >= 0.0f && 1-u-v>=0.0f && u>=0.0f && v>=0.0f)
return true;
return false;
}
mkdir build
cd build
cmake ..
make
./RayTracing