-
Notifications
You must be signed in to change notification settings - Fork 0
/
sphere.cpp
67 lines (58 loc) · 1.92 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
60
61
62
63
64
65
66
67
// Adapted from Realistic Ray Tracing
# include "sphere.h"
# include "Point3D.h"
# include "Ray3D.h"
#include "Texture.h"
# include <math.h>
# include <vector>
Sphere::Sphere(const Vector3D& ce, float r, Material* _material):
center(ce), radius(r), material(_material){}
bool Sphere::hit(const Ray3D& r, float tmin, float tmax, float time, HitRecord& record) const
{
Vector3D d = r.getDirection();
Vector3D e = r.getOrigin();
Vector3D c = center;
Vector3D diff = e-c;
double a = dotProduct(r.getDirection(), r.getDirection());
double discriminant = pow((2*dotProduct(d,diff)), 2) - 4*dotProduct(d,d)*( dotProduct(diff,diff) - radius*radius);
if (discriminant > 0)
{
discriminant = sqrt(discriminant);
double t = (- (2*(dotProduct(r.getDirection(), diff))) - discriminant) / (2*a);
if (t < tmin)
t = (- (2*(dotProduct(r.getDirection(), diff))) + discriminant) / (2*a);
if (t<tmin || t > tmax)
return false;
// there is a valid hit
record.t = t;
record.uvw.initFromW(unitVector(r.getOrigin() + t*r.getDirection() - center));
record.p = record.texp = r.pointAtParameter(t);
record.mat_ptr = material;
return true;
}
return false;
}
bool Sphere::shadowHit(const Ray3D& r, float tmin, float tmax, float time) const
{
Vector3D d = r.getDirection();
Vector3D e = r.getOrigin();
Vector3D c = center;
Vector3D diff = e-c;
double a = dotProduct(r.getDirection(), r.getDirection());
double discriminant = pow((2*dotProduct(d,diff)), 2) - 4*dotProduct(d,d)*( dotProduct(diff,diff) - radius*radius);
if(discriminant > 0) {
discriminant = sqrt(discriminant);
double t = (- (2*(dotProduct(r.getDirection(), diff))) - discriminant) / (2*a);
if (t < tmin)
t = (- (2*(dotProduct(r.getDirection(), diff))) + discriminant) / (2*a);
if (t<tmin || t > tmax)
return false;
return true;
}
return false;
}
void Sphere::printOut () const {
printf("center is: ");
center.printOut();
printf("radius is: %f", radius);
}