From 494b48c56017a28fb817eb639a85e542f5a9e710 Mon Sep 17 00:00:00 2001 From: Faerbit Date: Sat, 6 Jun 2020 14:47:39 +0200 Subject: [PATCH] Implemented diffuse reflection. --- vec3.h | 18 ++++++++++++++++++ wtracer.cpp | 22 ++++++++++++++-------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/vec3.h b/vec3.h index 04690c7..df7f98b 100644 --- a/vec3.h +++ b/vec3.h @@ -4,6 +4,8 @@ #include #include +#include "util.h" + class Vec3 { public: Vec3() : e{0, 0, 0} {} @@ -38,6 +40,14 @@ class Vec3 { return e[0] * e[0] + e[1] * e[1] + e[2] * e[2]; } + inline static Vec3 random() { + return Vec3(random_double(), random_double(), random_double()); + } + + inline static Vec3 random(double min, double max) { + return Vec3(random_double(min, max), random_double(min, max), random_double(min, max)); + } + private: double e[3]; @@ -102,4 +112,12 @@ inline Vec3 unit_vector(Vec3 v) { return v / v.length(); } +Vec3 random_in_unit_sphere() { + while (true) { + auto p = Vec3::random(-1, 1); + if (p.length_squared() >= 1) continue; + return p; + } +} + #endif // VEC3_H diff --git a/wtracer.cpp b/wtracer.cpp index 96b18d5..cf70ca0 100644 --- a/wtracer.cpp +++ b/wtracer.cpp @@ -9,10 +9,15 @@ #include "sphere.h" #include "camera.h" -Color ray_color(const Ray& r, const Hittable& world) { +Color ray_color(const Ray& r, const Hittable& world, int depth) { hit_record rec; + + if (depth <= 0) + return Color(0, 0, 0); + if (world.hit(r, 0, infinity, rec)) { - return 0.5 * (rec.normal + Color(1,1,1)); + Point3 target = rec.p + rec.normal + random_in_unit_sphere(); + return 0.5 * ray_color(Ray(rec.p, target - rec.p), world, depth-1); } Vec3 unit_direction = unit_vector(r.direction()); auto t = 0.5 * (unit_direction.y() + 1.0); @@ -21,10 +26,11 @@ Color ray_color(const Ray& r, const Hittable& world) { int main() { const auto aspect_ratio = 16.0 / 9.0; - const int image_width = 1280; - //const int image_width = 384; + //const int image_width = 1280; + const int image_width = 384; const int image_height = static_cast(image_width / aspect_ratio); - const int samples_per_pixel = 100; + const int samples_per_pixel = 250; + const int max_depth = 50; std::cout << "P3\n" << image_width << " " << image_height << "\n255\n"; @@ -39,10 +45,10 @@ int main() { for (int i = 0; i < image_width; ++i) { Color pixel_color(0, 0, 0); for (int s = 0; s