toytracer/moving_sphere.cpp

49 lines
1.7 KiB
C++

#include "moving_sphere.h"
#include "sphere.h"
Point3 Moving_sphere::center(double time) const {
return center0 + ((time - time0) / (time1 - time0)) * (center1 - center0);
}
bool Moving_sphere::hit(const Ray& r, double tmin, double tmax, hit_record& rec) const {
compute_sphere_uv((rec.p - center(r.time()))/radius, rec.u, rec.v);
Vec3 oc = r.origin() - center(r.time());
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(r.time())) / 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(r.time())) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
return true;
}
}
return false;
}
bool Moving_sphere::bounding_box(double t0, double t1, Aabb& output_box) const {
Aabb box0(
center(t0) - Vec3(radius, radius, radius),
center(t0) + Vec3(radius, radius, radius));
Aabb box1(
center(t1) - Vec3(radius, radius, radius),
center(t1) + Vec3(radius, radius, radius));
output_box = surrounding_box(box0, box1);
return true;
}