Ray tracing in a weekend (六)

将image plain的信息以及viewing ray的生成封装进camera class里

camera.h

#ifndef CAMERAH
#define CAMERAH

#include"ray.h"

//之前关于image plain的信息和viewing ray的生成
//都直接写在main里,现在要将它们封装进camera
//类里,毕竟image plain本来就是camera的可视范围
//而viewing ray也是由camera生成的
class camera
{
public:
	camera()
	{
		lower_left_corner = vec3(-2.0, -1.0, -1.0);
		horizontal = vec3(4.0, 0.0, 0.0);
		vertical = vec3(0.0, 2.0, 0.0);
		origin = vec3(0.0, 0.0, 0.0);
	}

	ray get_ray(float u, float v)
	{
		//直接写在main里时并没有最后减origin,那是因为origin为(0.0,0.0,0.0)
		//然而实际上是需要的
		return ray(origin, lower_left_corner + u*horizontal + v*vertical - origin);
	}
	vec3 origin;
	vec3 lower_left_corner;
	vec3 horizontal;
	vec3 vertical;
};

 抗锯齿处理:在每次取i/j时并不直接使用其整数(可以理解为间接的取一个pixel的sample point的过程),而是在这个整数向右偏差不超过1的范围里取100次小数作为i/j(在一个pixel中取一百个sample point),再将由这个i/j(射向一个pixel中一百个sample point的一百条ray)生成的color叠加起来最后除以100,从而达到averaging的目的,使得生成的图像的边缘pixel同时糅合了foreground和background,更加缓和,达到图形保真的目的。

#include"vector.h"
#include"ray.h"
#include"sphere.h"
#include"hitable_list.h"
#include"camera.h"
#include<random>
#include<cfloat>
#include<math.h>
#include<iostream>
#include<fstream>

using namespace std;

//此处的world就是把整个场景里的所有object视为一体(即hitable_list)
vec3 color(const ray& r,hitable *world)
{
	hit_record rec;
	if (world->hit(r, 0.0, FLT_MAX, rec))
	{
		return 0.5*vec3(rec.normal.x() + 1, rec.normal.y() + 1, rec.normal.z() + 1);
		//还是将交点处的normal映射为rgb颜色
	}
	vec3 unit_direction = unit_vector(r.direction());//得到单位方向向量,将y限定在-1至1之间
	float t = 0.5*(unit_direction.y() + 1.0);//间接用t代表y,将其限制在0至1之间
	return (1.0 - t)*vec3(1.0, 1.0, 1.0) + t*vec3(0.5, 0.7, 1.0);
    //所谓插值法,不同的ray对应的t不同,这些t决定了其对应的color为(1.0,1.0,1.0)和(0.5,0.7,1.0)之间某一RGB颜色
	//RGB各分量实际就是一个介于0.0至1.0的小数
}

float drand48()//伪
{
	return rand() % 10000 / 10000.0;
}
int main()
{
	int nx = 200;//200列
	int ny = 100;//100行
	int ns = 100;
	ofstream out("d:\\theFirstPpm.txt");
	out << "P3\n" << nx << " " << ny << "\n255" << endl;
	hitable *list[2];//我们自己定义world是什么,此处定义为两个sphere
	list[0] = new sphere(vec3(0, 0, -1), 0.5);
	list[1] = new sphere(vec3(0, -100.5, -1), 100);
	hitable *world = new hitable_list(list, 2);//初始化world
	camera cam;
	for (int j = ny - 1;j >= 0;j--)//行从上到下
	{
		for (int i = 0;i < nx;i++)//列从左到右
		{
			vec3 col(0, 0, 0);
			for (int s = 0;s < ns;s++)
			{
				float u = float(i + drand48()) / float(nx);
				float v = float(j + drand48()) / float(ny);
				ray r = cam.get_ray(u, v);
				vec3 p = r.point_at_parameter(2.0);
				col += color(r,world);
			}
			col /= float(ns);
			int ir = int(255.99*col[0]);
			int ig = int(255.99*col[1]);
			int ib = int(255.99*col[2]);
			out << ir << " " << ig << " " << ib << endl;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/UIUCGOGOGO/article/details/82844036