-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSphere.cpp
36 lines (29 loc) · 874 Bytes
/
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
#include "Sphere.hpp"
#include "Hit.hpp"
Sphere::Sphere(Vec3 center, float radius, std::shared_ptr<Material> m)
:Hittable(m),mCenter(center), mRadius(radius)
{
}
bool Sphere::hit(const Ray &r, float tMin, float tMax, Hit &rec) const
{
//t^2 * b*b + 2t * b(A-C) + (A-C)^2 -r^2 = 0
Vec3 oc = r.origin - mCenter;
auto a = r.direction.lengthSquared();
auto halfB = dot(r.direction, oc);
auto c = oc.lengthSquared() - mRadius*mRadius;
auto discriminant = halfB*halfB - a*c;
if(discriminant < 0) return false;
auto sqrtd = std::sqrt(discriminant);
auto t = (-halfB - sqrtd)/a;
if(t<tMin || t>tMax)
{
t = (-halfB + sqrtd)/a;
if(t<tMin || t>tMax)
return false;
}
rec.t = t;
rec.p = r.at(rec.t);
rec.setFaceNormal(r, rec.p - mCenter);
rec.material = mMaterial;
return true;
}