作业5 光线与三角形相交

作业5介绍

enter image description here

简单来说就是,为每个像素生成光线,然后判断光线和三角形相交。我们只需要写Render()、rayTriangleIntersect(),第二个还好,直接按着课上给的算法写就好, 第一个需要把像素坐标转化为[-1,1],相当于是作业1的一个逆变换,首先压缩为[0,1],然后变成[-1,1],最后因为屏幕像素长宽不一样,所以需要乘一个长宽比, 然后视角是多少度还需要乘tan(fov/2)。视角就取决于你看到的y的大小,摄像机是有角度的。

关于怎么生成相机光线

code

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 y = dotProduct(S1,E1);
    tnear = dotProduct(S2,E2)/y;
    u = dotProduct(S1,S)/y;
    v = dotProduct(S2,dir)/y;
    if(tnear>1e-6&&u>1e-6&&v>1e-6&&1-u-v>1e-6) {
        return true;
    }
    return false;
}

 // generate primary ray direction
            float x;
            float y;
            x = i + 0.5;
            y = j + 0.5;
            x/= float(scene.width);
            y/= float(scene.height);
            x = 2*x - 1;
            y = 1 - 2*y;
            x = x*scale*imageAspectRatio;
            y = y*scale;
            // 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*            

            Vector3f dir = Vector3f(x, y, -1); // Don't forget to normalize this direction!
            dir = normalize(dir);
            framebuffer[m++] = castRay(eye_pos, dir, scene, 0);