-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphere.h
87 lines (66 loc) · 2.29 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#ifndef SPHERE_H
#define SPHERE_H
#include "rtweekend.h"
#include "hittable.h"
class sphere : public hittable {
public:
sphere(const point3& _center, double _radius, shared_ptr<material> _material)
: center1(_center), radius(_radius), mat(_material), is_moving(false)
{
auto rvec = vec3(radius, radius, radius);
bbox = aabb(center1 - rvec, center1 + rvec);
}
sphere(const point3& _center1, const point3& _center2, double _radius,
shared_ptr<material> _material)
: center1(_center1), radius(_radius), mat(_material), is_moving(true)
{
auto rvec = vec3(radius, radius, radius);
aabb box1(_center1 - rvec, _center1 + rvec);
aabb box2(_center2 - rvec, _center2 + rvec);
bbox = aabb(box1, box2);
center_vec = _center2 - _center1;
}
bool hit(const ray& r, interval ray_t, hit_record& rec) const override {
point3 center = is_moving ? sphere_center(r.time()) : center1;
vec3 oc = center - r.origin();
auto a = r.direction().length_squared();
auto h = dot(r.direction(), oc);
auto c = oc.length_squared() - radius*radius;
auto discriminant = h*h - a*c;
if (discriminant < 0)
return false;
// Find the nearest root that lies in the acceptable range.
auto sqrtd = sqrt(discriminant);
auto root = (h - sqrtd) / a;
if (!ray_t.surrounds(root)) {
root = (h + sqrtd) / a;
if (!ray_t.surrounds(root))
return false;
}
rec.t = root;
rec.p = r.at(rec.t);
vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
get_sphere_uv(outward_normal, rec.u, rec.v);
rec.mat = mat;
return true;
}
aabb bounding_box() const override { return bbox; }
private:
point3 center1;
double radius;
shared_ptr<material> mat;
bool is_moving;
vec3 center_vec;
aabb bbox;
point3 sphere_center(double time) const {
return center1 + time*center_vec;
}
static void get_sphere_uv(const point3& p, double& u, double& v) {
auto theta = acos(-p.y());
auto phi = atan2(-p.z(), p.x()) + pi;
u = phi / (2*pi);
v = theta / pi;
}
};
#endif