You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.8 KiB
60 lines
1.8 KiB
#include <cmath>
|
|
#include <fstream>
|
|
#include <iostream>
|
|
|
|
#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
|
|
cout << t << " " << I * dot(N, L) << endl;
|
|
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;
|
|
|
|
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";
|
|
for (int j = height - 1; j >= 0; j--) {
|
|
for (int i = 0; i < width; i++) {
|
|
float u = float(i) / float(width);
|
|
float v = float(j) / float(height);
|
|
ray r = ray(origin, lower_left_corner + u * horizontal + v * vertical);
|
|
vec3 color2 = color(r);
|
|
file << int(color2.r() * 255) << " " << int(color2.g() * 255) << " " << int(color2.b() * 255) << "\n";
|
|
}
|
|
}
|
|
file.close();
|
|
} |