Implement sphere normals.

This commit is contained in:
Faerbit 2020-06-03 23:25:47 +02:00
parent 9f4868917d
commit 9e16d5f112

View File

@ -1,23 +1,32 @@
#include <iostream> #include <iostream>
#include <cmath>
#include "color.h" #include "color.h"
#include "vec3.h" #include "vec3.h"
#include "ray.h" #include "ray.h"
bool hit_sphere(const Point3& center, double radius, const Ray& r) { double hit_sphere(const Point3& center, double radius, const Ray& r) {
Vec3 oc = r.origin() - center; Vec3 oc = r.origin() - center;
auto a = dot(r.direction(), r.direction()); auto a = dot(r.direction(), r.direction());
auto b = 2.0 * dot(oc, r.direction()); auto b = 2.0 * dot(oc, r.direction());
auto c = dot(oc, oc) - radius * radius; auto c = dot(oc, oc) - radius * radius;
auto disciminant = b*b - 4*a*c; auto disciminant = b*b - 4*a*c;
return disciminant > 0; if (disciminant < 0) {
return -1.0;
} else {
return (-b - std::sqrt(disciminant)) / (2.0 * a);
}
} }
Color ray_color(const Ray& r) { Color ray_color(const Ray& r) {
if (hit_sphere(Point3(0, 0, -1), 0.5, r)) auto sphere_center = Point3(0, 0, -1);
return Color(1, 0, 0); auto t = hit_sphere(sphere_center, 0.5, r);
if (t > 0.0) {
Vec3 n = unit_vector(r.at(t) - sphere_center);
return 0.5 * Color(n.x()+1, n.y()+1, n.z()+1);
}
Vec3 unit_direction = unit_vector(r.direction()); Vec3 unit_direction = unit_vector(r.direction());
auto t = 0.5 * (unit_direction.y() + 1.0); t = 0.5 * (unit_direction.y() + 1.0);
return (1.0 - t) * Color(1.0, 1.0, 1.0) + t * Color(0.5, 0.7, 1.0); return (1.0 - t) * Color(1.0, 1.0, 1.0) + t * Color(0.5, 0.7, 1.0);
} }