cpp-raytracer/main.cpp

89 lines
2.3 KiB
C++

#include <stdio.h>
#include <stdint.h>
#include "rtweekend.hpp"
#include "color.hpp"
#include "hittable_list.hpp"
#include "sphere.hpp"
#include "camera.hpp"
color ray_color(const ray& r, const hittable& world);
double hit_sphere(const point3& center, double radius, const ray& r);
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 = normalize(r.direction);
double t = 0.5 * (unit_direction.y + 1.0);
return (1-t) * color(1,1,1) + t*color(0.5,0.7,1.0);
}
double hit_sphere(const point3& center, double radius, const ray& r)
{
vec3 oc = r.origin - center;
double a = r.direction.length_squared();
double half_b = dot(oc, r.direction);
double c = oc.length_squared() - radius*radius;
double discriminant = half_b*half_b - a*c;
if (discriminant < 0)
return -1;
else
return (-half_b - sqrt(discriminant)) / a;
}
int main()
{
// Image
double aspect_ratio = 16.0 / 9;
const int32_t image_width = 400;
const int32_t image_height = (int32_t) (image_width / aspect_ratio);
int32_t samples_per_pixel = 100;
if (getenv("SPP"))
{
samples_per_pixel = strtol(getenv("SPP"), NULL, 10);
}
// World
hittable_list world;
world.add(std::make_shared<sphere>(point3(0,0,-1), 0.5));
world.add(std::make_shared<sphere>(point3(0,-100.5,-1), 100));
// Camera
camera cam;
// Render
printf("P3\n%d %d\n255\n", image_width, image_height);
for (int32_t j = image_height - 1; j >= 0; --j)
{
fprintf(stderr, "\rScanlines remaining: %d ", j);
fflush(stderr);
for (int32_t i = 0; i < image_width; ++i)
{
color pixel_color = color(0,0,0);
for (int32_t s = 0; s < samples_per_pixel; ++s)
{
double u = ((i + random_double()) / (image_width-1));
double v = ((j + random_double()) / (image_height-1));
ray r = cam.get_ray(u,v);
pixel_color += ray_color(r, world);
}
write_color(stdout, pixel_color, samples_per_pixel);
}
}
fprintf(stderr, "\nDone\n");
}