-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsphere.h
More file actions
42 lines (32 loc) · 1.18 KB
/
sphere.h
File metadata and controls
42 lines (32 loc) · 1.18 KB
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
#ifndef SPHERE_H
#define SPHERE_H
#include "hittable.h"
class sphere : public hittable {
public:
sphere(const point3& center, double radius) : center(center), radius(std::fmax(0, radius)) {}
bool hit(const ray& r, interval rayT, hitRecord& rec) const override {
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;
auto sqrtd = std::sqrt(discriminant);
// Find the nearest root that lies in the acceptable range.
auto root = (h - sqrtd) / a;
if (!rayT.surrounds(root)) {
root = (h + sqrtd) / a;
if (!rayT.surrounds(root))
return false;
}
rec.t = root;
rec.p = r.at(rec.t);
vec3 outwardNormal = (rec.p - center) / radius;
rec.setFaceNormal(r, outwardNormal);
return true;
}
private:
point3 center;
double radius;
};
#endif