toytracer/wtracer.cpp

48 lines
1.6 KiB
C++
Raw Normal View History

2020-06-02 22:06:53 +00:00
#include <iostream>
2020-06-03 21:25:47 +00:00
#include <cmath>
2020-06-02 22:06:53 +00:00
#include "color.h"
#include "vec3.h"
2020-06-03 20:39:40 +00:00
#include "ray.h"
Color ray_color(const Ray& r) {
2020-06-03 21:25:47 +00:00
auto sphere_center = Point3(0, 0, -1);
auto t = hit_sphere(sphere_center, 0.5, r);
if (t > 0.0) {
Vec3 n = unit_vector(r.at(t) - sphere_center);
return 0.5 * Color(n.x()+1, n.y()+1, n.z()+1);
}
2020-06-03 20:39:40 +00:00
Vec3 unit_direction = unit_vector(r.direction());
2020-06-03 21:25:47 +00:00
t = 0.5 * (unit_direction.y() + 1.0);
2020-06-03 20:39:40 +00:00
return (1.0 - t) * Color(1.0, 1.0, 1.0) + t * Color(0.5, 0.7, 1.0);
}
2020-06-02 22:06:53 +00:00
int main() {
2020-06-03 20:39:40 +00:00
const auto aspect_ratio = 16.0 / 9.0;
const int image_width = 1280;
const int image_height = static_cast<int>(image_width / aspect_ratio);
2020-06-02 22:06:53 +00:00
std::cout << "P3\n" << image_width << " " << image_height << "\n255\n";
2020-06-03 20:39:40 +00:00
auto viewport_height = 2.0;
auto viewport_width = aspect_ratio * viewport_height;
auto focal_length = 1.0;
auto origin = Point3(0, 0, 0);
auto horizontal = Vec3(viewport_width, 0, 0);
auto vertical = Vec3(0, viewport_height, 0);
auto lower_left_corner = origin - horizontal/2 - vertical/2 - Vec3(0, 0, focal_length);
2020-06-02 22:06:53 +00:00
for (int j = image_height - 1; j >= 0; --j) {
std::cerr << "\rScanlines remaining: " << j << " " << std::flush;
for (int i = 0; i < image_width; ++i) {
2020-06-03 20:39:40 +00:00
auto u = double(i) / (image_width - 1);
auto v = double(j) / (image_height - 1);
Ray r(origin, lower_left_corner + u*horizontal + v*vertical - origin);
Color pixel_color = ray_color(r);
2020-06-02 22:06:53 +00:00
write_color(std::cout, pixel_color);
}
}
std::cerr << "\nDone.\n";
}