Ray Tracing in One Weekend Part3

完成到第七章抗锯齿的内容

#include <iostream>
#include<fstream>
#include<string>
#include "v3d.h"
#include "ray.h"
#include "color.h"
#include "rtweekend.h"
#include "hittable_list.h"
#include "sphere.h"
#include"camera.h"
using namespace std;
// Type aliases for vec3
using point3 = vec3;   // 3D point
using color = vec3;    // RGB color


double hit_sphere(const point3& center, double radius, const ray& r) {
	vec3 oc = r.origin() - center;
	auto a = r.direction().length_squared();//t2b⋅b+2tb⋅(A−C)+(A−C)⋅(A−C)−r2=0 函数关于t, P(t)=A+tb
	auto half_b = dot(oc, r.direction());
	auto c = oc.length_squared() - radius * radius;
	auto discriminant = half_b * half_b - a * c;
	if (discriminant < 0) {
		return -1.0;
	}
	else {
		return (-half_b - sqrt(discriminant)) / a;
	}
}



color ray_color(const ray& r ,const hittable& world) {
	hit_record rec;
	if (world.hit(r, 0, infinity, rec)){//如果打中了球,在球的范围内,就变成彩色
		return 0.5 * (rec.normal + color(1, 1, 1));
	}
	vec3 unit_direction = unit_vector(r.direction());
	//显示蓝色背景
	auto back = 0.5 * (unit_direction.y() + 1.0);
	return (1.0 - back) * color(1.0, 1.0, 1.0) + back * color(0.5, 0.7, 1.0);
}

int main()
{
	// Image
	const auto aspect_ratio = 16.0 / 9.0;
	const int image_width = 400;
	const int image_height = static_cast<int>(image_width / aspect_ratio);
	const int sample_per_pixel = 100;//采样次数

	// World
	hittable_list world;
	world.add(make_shared<sphere>(point3(0, 0, -1), 0.5));
	world.add(make_shared<sphere>(point3(0, -100.5, -1), 100));

	// Camera
	camera cam;//定义函数放到头文件里面了

	// Render
	ofstream file("graph1-2.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 pix_color(0, 0, 0);
			for (int s = 0; s < sample_per_pixel; s++) {//采样100次,即图片的每个点位都发出的光通过random随机不同方向,取样100次求平均值
				auto u = (i + random_double()) / (image_width - 1);
				auto v = (j + random_double()) / (image_height - 1);
				ray r = cam.get_ray(u, v);
				pix_color += ray_color(r, world);
			}
			write_color(file, pix_color,sample_per_pixel);
		}
	}

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

  

 

 

 

posted @ 2022-07-08 22:28  LOFU  阅读(12)  评论(0编辑  收藏  举报