Ray Tracing in One Weekend Part1

官方教程:Ray Tracing in One Weekend

参考:【Ray Tracing in One Weekend 超详解】 光线追踪1-1 之美 - 灰信网(软件开发博客聚合) (freesion.com)

任务2 Output an Image及任务3 The vec3 Class

#include <iostream>
#include<fstream>
#include<string>
#include "v3d.h"
using namespace std;

void build_1_1()
{
	int nx = 200;
	int ny = 100;

	ofstream file("graph1-1.ppm");//如果window系统可以在ps中打开ppm文件,需要从cout变换输出流为ppm
	if (file.is_open())
	{
		file << "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;
				int ir = int(255.99 * r);
				int ig = int(255.99 * g);
				int ib = int(255.99 * b);
				string res = to_string(ir) + " " + to_string(ig) + " " + to_string(ib);
				file << res << endl;
			}
		}
		file.close();
	}
}

void write_color(std::ostream& out, color pixel_color) {
	// Write the translated [0,255] value of each color component.
	out << static_cast<int>(255.999 * pixel_color.x()) << ' '
		<< static_cast<int>(255.999 * pixel_color.y()) << ' '
		<< static_cast<int>(255.999 * pixel_color.z()) << '\n';
}

int main()
{
	//build_1_1();
	const int image_width = 256;
	const int image_height = 256;

	// Render
	ofstream file("graph1-1.ppm");
	file << "P3\n" << image_width << ' ' << image_height << "\n255\n";

	for (int j = image_height - 1; j >= 0; --j) {
		std::cerr << "\rScanlines remaining: " << j << ' ' << std::flush;
		for (int i = 0; i < image_width; ++i) {
			color pixel_color(double(i) / (image_width - 1), double(j) / (image_height - 1), 0.25);
			write_color(file, pixel_color);
		}
	}

	std::cerr << "\nDone.\n";
}

  

posted @ 2022-06-26 17:08  LOFU  阅读(20)  评论(0编辑  收藏  举报