-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphere.h
42 lines (38 loc) · 1.04 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
#pragma once
#include "hitable.h"
class Sphere :public Hitable {
public:
Sphere(){}
Sphere(Vec3 cen, float r, Material* m) :center(cen), radius(r), matPtr(m) {};
virtual bool Hit(const Ray& r, float tMin, float tMax, HitRecord& rec)const;
private:
Vec3 center;
float radius;
Material *matPtr;
};
bool Sphere::Hit(const Ray& r, float tMin, float tMax, HitRecord& rec) const {
Vec3 oc = r.Origin() - center;
float a = Dot(r.Direction(), r.Direction());
float b = Dot(oc, r.Direction());
float c = Dot(oc, oc) - radius * radius;
float discriminant = b * b - a * c;
if (discriminant > 0) {
float temp = (-b - sqrt(b*b - a * c)) / a;
if (temp < tMax && temp > tMin) {
rec.t = temp;
rec.p = r.PointAtParameter(rec.t);
rec.normal = (rec.p - center) / radius;
rec.matPtr = matPtr;
return true;
}
temp = (-b + sqrt(b*b - a * c)) / a;
if (temp < tMax && temp > tMin) {
rec.t = temp;
rec.p = r.PointAtParameter(rec.t);
rec.normal = (rec.p - center) / radius;
rec.matPtr = matPtr;
return true;
}
}
return false;
}