-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphere.cpp
60 lines (47 loc) · 1.15 KB
/
sphere.cpp
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
#include "sphere.hpp"
using namespace strangeloop;
Sphere::Sphere()
:_center(0,0,0),_radius(0.0)
{
}
Sphere::Sphere(Point center, double r)
:_center(center), _radius(r)
{
}
Sphere::Sphere(Point center, double r, std::shared_ptr<Material> m)
:_center(center), _radius(r), _material(m)
{
}
bool Sphere::hit(const strangeloop::Ray &r, double tMin, double tMax, strangeloop::HitRecord &rec) const
{
Vector3 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 d = half_b*half_b - a*c;
if (d < 0) {
return false;
}
auto sqrtd = sqrt(d);
auto root = (-half_b - sqrtd) / a;
if (root < tMin || root > tMax) {
root = -(half_b + sqrtd) / a;
if (root < tMin || root > tMax) {
return false;
}
}
rec.t = root;
rec.p = r.at(rec.t);
Vector3 normal = (rec.p - _center)/_radius;
rec.faceNormal(r,normal);
rec.material = _material;
return true;
}
Point Sphere::center() const
{
return _center;
}
double Sphere::radius() const
{
return _radius;
}