-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSphere.h
43 lines (37 loc) · 1.01 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
#pragma once
#include "Hittable.h"
class Sphere : public Hittable {
public:
Sphere(const Point3& center, double radius, std::shared_ptr<Material> mat)
: center(center), radius(std::fmax(0,radius)), mat(mat)
{}
bool hit(const Ray& r, Interval ray_t, Hit_Record& 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 (!ray_t.surrounds(root)) {
root = (h + sqrtd) / a;
if (!ray_t.surrounds(root))
return false;
}
/*
6.4*/
rec.t = root;
rec.p = r.at(rec.t);
Vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat = mat;
return true;
}
private:
Point3 center;
double radius;
std::shared_ptr<Material> mat;
};