#include #include #include #include "ray.h" #include "vec3.h" using namespace std; //skybox float hit_sphere(const vec3& center, float radius, const ray& r) { float a, b, c, t; a = dot(r.D, r.D); b = 2 * (dot(r.D, (r.O - center))); c = dot(r.O - center, r.O - center) - radius * radius; t = (((-b) - sqrt((b * b) - (4 * a * c))) / (2 * a)); //cout << a << " " << b << " " << c; return t >= 0 ? t : 0; } vec3 color(ray& r) { vec3 center(0, 0, -1); float t = hit_sphere(center, 0.5, r); if (t > 0.0) { vec3 N = unit_vector(r.point_at_parameter(t) - center); vec3 L = unit_vector(vec3(1, 1, 0) - r.point_at_parameter(t)); vec3 I = vec3(1, 1, 1); //intensity of lightsource return (dot(N, L) > 0 ? dot(N, L) : 0) * I; } vec3 unit_direction = unit_vector(r.direction()); t = 0.5 * (unit_direction.y() + 1.0); return (1.0 - t) * vec3(1, 1, 1) + t * vec3(0.5, 0.7, 1.0); } int main() { int width = 200; int height = 100; int anti_aliasing_scale = 5; fstream file; file.open("ray.ppm", ios::out); vec3 lower_left_corner(-2, -1, -1); vec3 origin(0, 0, 0); vec3 horizontal(4, 0, 0); vec3 vertical(0, 2, 0); file << "P3\n" << width << " " << height << "\n255\n"; vec3** colors = new vec3*[height * anti_aliasing_scale]; for (int i = 0; i < height * anti_aliasing_scale; i++) { colors[i] = new vec3[width * anti_aliasing_scale]; } for (int j = (height * anti_aliasing_scale) - 1; j >= 0; j--) { for (int i = 0; i < (width * anti_aliasing_scale); i++) { float u = float(i) / float(width * anti_aliasing_scale); float v = float(j) / float(height * anti_aliasing_scale); ray r = ray(origin, lower_left_corner + u * horizontal + v * vertical); vec3 color2 = color(r); colors[j][i] = color2 * 255; } } for (int j = height - 1; j >= 0; j--) { for (int i = 0; i < width; i++) { vec3 color3 = vec3(0, 0, 0); for (int a = 0; a < anti_aliasing_scale; a++) { for (int b = 0; b < anti_aliasing_scale; b++) { color3 = vec3(color3.r() + colors[j * anti_aliasing_scale + a][i * anti_aliasing_scale + b].r(), color3.g() + colors[j * anti_aliasing_scale + a][i * anti_aliasing_scale + b].g(), color3.b() + colors[j * anti_aliasing_scale + a][i * anti_aliasing_scale + b].b()); } } color3 = vec3(color3.r() / (anti_aliasing_scale * anti_aliasing_scale), color3.g() / (anti_aliasing_scale * anti_aliasing_scale), color3.b() / (anti_aliasing_scale * anti_aliasing_scale)); file << int(color3.r()) << " " << int(color3.g()) << " " << int(color3.b()) << "\n"; } } file.close(); }