-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoving_sphere.h
40 lines (37 loc) · 1.78 KB
/
moving_sphere.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#ifndef MOVING_SPHERE_H
#define MOVING_SPHERE_H
#include "hittable.h"
#include "vec3.h"
struct moving_sphere : public hittable {
moving_sphere() {}
moving_sphere(point3 cen0, point3 cen1, double _time0, double _time1, double r, std::shared_ptr<material> m)
: center0(cen0), center1(cen1), time0(_time0), time1(_time1), radius(r), mat_ptr(m) {};
point3 center0, center1;
double time0, time1, radius;
std::shared_ptr<material> mat_ptr;
bool hit(const ray& r, double t_min, double t_max, hit_record& rec) const {
vec3 oc = r.origin() - center(r.time()); // (A + tB - C).(A + tB - C) = r^2 => B^2t^2 + 2ABt + A^2 - r^2 = 0
auto a = r.direction().length_squared(), half_b = dot(oc, r.direction()), c = oc.length_squared() - radius*radius;
auto discriminant = half_b*half_b - a*c;
if (discriminant < 0) return false;
auto sqrtd = sqrt(discriminant), root = (-half_b - sqrtd)/a;
if (root < t_min || t_max < root) {
root = (-half_b + sqrtd)/a;
if (root < t_min || t_max < root) return false;
}
rec.t = root;
rec.p = r.at(rec.t);
auto outward_normal = (rec.p - center(r.time()))/radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
return true;
}
point3 center(double time) const {return center0 + (time - time0)/(time1 - time0)*(center1 - center0);}
bool bounding_box(double _time0, double _time1, aabb& output_box) const {
aabb box0(center(_time0) - vec3(radius, radius, radius), center(_time0) + vec3(radius, radius, radius));
aabb box1(center(_time1) - vec3(radius, radius, radius), center(_time1) + vec3(radius, radius, radius));
output_box = surrounding_box(box0, box1);
return true;
}
};
#endif