#include #include #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, int32_t depth); double hit_sphere(const point3& center, double radius, const ray& r); color ray_color(const ray& r, const hittable& world, int32_t depth) { if (depth <= 0) { return color(0,0,0); } hit_record rec; if (world.hit(r, 0.001, INFINITY, rec)) { ray scattered; color attenuation; if (rec.mat_ptr->scatter(r, rec, attenuation, scattered)) { return attenuation * ray_color(scattered, world, depth-1); } else { return color(0,0,0); } } 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; int32_t max_depth = 50; if (getenv("SPP")) { samples_per_pixel = strtol(getenv("SPP"), NULL, 10); } // World hittable_list world; std::shared_ptr material_ground = make_shared(color(0.8, 0.8, 0.0)); std::shared_ptr material_center = make_shared(color(0.7, 0.3, 0.3)); std::shared_ptr material_left = make_shared(color(0.8, 0.8, 0.8), 0.3); std::shared_ptr material_right = make_shared(color(0.8, 0.6, 0.2), 1.0); world.add(make_shared(point3( 0.0, -100.5, -1.0), 100.0, material_ground)); world.add(make_shared(point3( 0.0, 0.0, -1.0), 0.5, material_center)); world.add(make_shared(point3(-1.0, 0.0, -1.0), 0.5, material_left)); world.add(make_shared(point3( 1.0, 0.0, -1.0), 0.5, material_right)); // 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, max_depth); } write_color(stdout, pixel_color, samples_per_pixel); } } fprintf(stderr, "\nDone\n"); }