通过射线跟踪制作JPG(一个周末进行射线跟踪)

时间:2018-10-15 23:15:33

标签: c++ raytracing stb-image

我正在关注《周末的光线追踪》(Ray Tracing)一书,该书的作者使用普通C ++生成了一个小的Ray Tracer,结果是一个 PPM图像

作者的代码
The author's code

哪个会生成此PPM图像。
Which produces this PPM image.

因此,作者建议作为练习,以使程序通过stb_image库生成 JPG图片。到目前为止,我尝试通过更改原始代码来实现:

#include <fstream>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

struct RGB{
    unsigned char R;
    unsigned char G;
    unsigned char B;
};

int main(){
    int nx = 200;
    int ny = 100;

    struct RGB data[nx][ny];

    for(int j = ny - 1 ; j >= 0 ; j-- ){
        for(int i = 0; i < nx ; i++){

            float r = float(i) / float(nx);
            float g = float(j) / float(ny);
            float b = 0.2;

            int ir = int(255.99 * r);
            int ig = int(255.99 * g);
            int ib = int(255.99 * b);

            data[i][j].R = ir;
            data[i][j].G = ig;
            data[i][j].B = ib;
        }
    }
    stbi_write_jpg("image.jpg", nx, ny, 3, data, 100);
}

这是结果:And this is the result

您可以看到我的结果略有不同,我不知道为什么。 主要问题是:

  1. 黑色显示在屏幕的左上方,通常,颜色的显示顺序不正确,从左到右,从上到下。

  2. 图像被“分割”成两半,结果实际上是作者的原始图像,但成对出现????

可能我对应该使用STB_IMAGE_WRITE的方式有误解,所以如果有任何使用此库的经验的人可以告诉我怎么回事,我将不胜感激。

编辑1 我实现了@ 1201ProgramAlarm在注释中建议的更改,并且我将struct RGB data[nx][ny]更改为struct RGB data[ny][nx]so the result now is this

2 个答案:

答案 0 :(得分:0)

您为data编制的索引错误。内部循环变量应为第二个下标(data[j][i])。

答案 1 :(得分:0)

库应按预期运行。问题在于如何提供数据以及应该做的是反转y轴。因此,当您从一开始就在索引4处时,应该从结尾给出索引4的颜色。

从编辑中获取结果,只需更改以下行:

float g = float(j) / float(ny);

float g = float(ny - 1 - j) / float(ny);