该函数是渲染器的主要函数,用于遍历图像中的所有像素,并生成主光线并将这些光线投射到场景中。渲染结果保存在帧缓冲区中,并保存为文件。

在函数内部,首先创建一个大小为'场景宽度 x 场景高度'的帧缓冲区。然后,使用视野角度(即FOV)计算比例因子,并计算图像的宽高比。接下来,使用初始眼睛位置(即(0,0,0))创建一个循环,遍历每个像素。对于每个像素,计算出通过它的光线方向,并将其保存在一个Vector3f对象中。然后使用该方向调用castRay函数,该函数将返回该光线在场景中的颜色值,并将其存储在帧缓冲区中的相应位置。最后,将帧缓冲区中的内容保存到名为'binary.ppm'的文件中。

需要注意的是,x和y的计算使用了当前像素的位置,因此需要将其归一化为[0,1]的范围。此外,生成的光线方向需要进行归一化处理。

代码示例:

// [comment]
// The main render function. This where we iterate over all pixels in the image, generate
// primary rays and cast these rays into the scene. The content of the framebuffer is
// saved to a file.
// [/comment]
void Renderer::Render(const Scene& scene)
{
    std::vector<Vector3f> framebuffer(scene.width * scene.height);
 
    //
    float scale = std::tan(deg2rad(scene.fov * 0.5f));
    //宽高比
    float imageAspectRatio = (float)scene.width / (float)scene.height;
 
    // Use this variable as the eye position to start your rays.
    Vector3f eye_pos(0);
    int m = 0;
    for (int j = 0; j < scene.height; ++j)
    {
        for (int i = 0; i < scene.width; ++i)
        {
            // generate primary ray direction
            float x = (2*(((float)i+0.5)/scene.width-1) * imageAspectRatio * scale;
            float y = (1.0-2*((float)j+0.5)/scene.height) * 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*    
               
            //vector = op,说明scene在z=-1,故znear距离人眼距离=1   
            Vector3f dir = normalize(Vector3f(x, y, -1)); // Don't forget to normalize this direction!
            framebuffer[m++] = castRay(eye_pos, dir, scene, 0);
        }
        UpdateProgress(j / (float)scene.height);
    }
 
    // save framebuffer to file
    FILE* fp = fopen("binary.ppm", "wb");
    (void)fprintf(fp, "P6\n%d %d\n255\n", scene.width, scene.height);
    for (auto i = 0; i < scene.height * scene.width; ++i) {
        static unsigned char color[3];
        color[0] = (char)(255 * clamp(0, 1, framebuffer[i].x));
        color[1] = (char)(255 * clamp(0, 1, framebuffer[i].y));
        color[2] = (char)(255 * clamp(0, 1, framebuffer[i].z));
        fwrite(color, 1, 3, fp);
    }
    fclose(fp);    
}
C++ 渲染器主函数:Render() 的详细解析

原文地址: https://www.cveoy.top/t/topic/ofmJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录