您的位置:首页 > 编程语言 > C语言/C++

【Ray Tracing in One Weekend】(ch0~1)c++生成的第一张图片

2017-11-10 13:13 1051 查看

Chapter 0: Overview

作者讲了讲自己的教学经验以及有关光线追踪的一些事。

作者推荐我们使用c++。

Chapter 1: Output an image

展示了如何用代码生成第一张图片。用到了PPM格式。



这里 有PPM格式的详解。

书中实例代码如下(添加了输出到 txt 文件的代码,原代码只输出到命令行):

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
ofstream outfile;
outfile.open("firstImage.txt");

int nx = 200;
int ny = 100;
outfile << "P3\n" << nx << " " << ny << "\n255\n";
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.2f;

int ir = int(255.99f*r);
int ig = int(255.99f*g);
int ib = int(255.99f*b);
outfile << ir << " " << ig << " " << ib << "\n";
}
}
outfile.close();
return 0;
}


输出结果如下,拷贝 firstImage.txt 并修改后缀为 .ppm。



使用 Photoshop CC 2017 打开后,如图所示:



从如下三行代码中我们可以看到:

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


在RGB三色通道中,从上到下,绿色通道值减小;从左到右,红色通道值增加;而蓝色通道值不变。所得图片即上图。

我们可以在 Photoshop 中验证一下:

把蓝色通道值,即 B 固定为51,我们发现左边的拾色盘跟我们的图片一模一样。从上到下,G 值减小;从左到右,R 值增加。右上角为黄色(255,255,51)。



那如果我们想得到如下图中拾色盘中的图片,该怎么做呢?



观察得,R 值固定为100,从左到右 B 值增加,从上到下,G 值减小。则修改代码为:

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

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


所得图片如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: