40 lines
1.3 KiB
C++
40 lines
1.3 KiB
C++
#include "sphere.h"
|
|
|
|
bool Sphere::hit(const Ray& r, double tmin, double tmax, hit_record& rec) const {
|
|
compute_sphere_uv((rec.p - center)/radius, rec.u, rec.v);
|
|
Vec3 oc = r.origin() - center;
|
|
auto a = r.direction().length_squared();
|
|
auto half_b = dot(oc, r.direction());
|
|
auto c = oc.length_squared() - radius * radius;
|
|
auto discriminant = half_b*half_b - a*c;
|
|
if (discriminant > 0) {
|
|
auto root = std::sqrt(discriminant);
|
|
auto temp = (-half_b - root) / a;
|
|
if (temp < tmax && temp > tmin) {
|
|
rec.t = temp;
|
|
rec.p = r.at(rec.t);
|
|
Vec3 outward_normal = (rec.p - center) / radius;
|
|
rec.set_face_normal(r, outward_normal);
|
|
rec.mat_ptr = mat_ptr;
|
|
return true;
|
|
}
|
|
temp = (-half_b + root) / a;
|
|
if (temp < tmax && temp > tmin) {
|
|
rec.t = temp;
|
|
rec.p = r.at(rec.t);
|
|
Vec3 outward_normal = (rec.p - center) / radius;
|
|
rec.set_face_normal(r, outward_normal);
|
|
rec.mat_ptr = mat_ptr;
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
bool Sphere::bounding_box(double t0, double t1, Aabb& output_box) const {
|
|
output_box = Aabb(
|
|
center - Vec3(radius, radius, radius),
|
|
center + Vec3(radius, radius, radius));
|
|
return true;
|
|
}
|