-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sphere.cpp
68 lines (54 loc) · 1.49 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
68
#include "Sphere.h"
Sphere::Sphere(const Vector3 ¢er, float radius, Material *material)
:center(center), radius(radius), material(material)
{
bbox.min.x = center.x - radius;
bbox.min.y = center.y - radius;
bbox.min.z = center.z - radius;
bbox.max.x = center.x + radius;
bbox.max.y = center.y + radius;
bbox.max.z = center.z + radius;
}
bool Sphere::Hit(const Ray &r, float tmin, float tmax, float time, HitRecord &record) const
{
Vector3 temp = r.o - center;
double a = Dot(r.d, r.d);
double b = 2 * Dot(r.d, temp);
double c = Dot(temp, temp) - radius*radius;
double discriminant = b*b - 4 * a*c;
if (discriminant > 0)
{
discriminant = sqrt(discriminant);
double t = (-b - discriminant) / (2 * a);
if (t < tmin)
t = (-b + discriminant) / (2 * a);
if (t<tmin || t>tmax)
return false;
record.t = t;
record.pos = r.o + t*r.d;
//record.normal = UnitVector(r.o + t*r.d - center);
record.uvw.InitFromW(r.o + t*r.d - center);
record.material = material;
return true;
}
return false;
}
bool Sphere::ShadowHit(const Ray &r, float tmin, float tmax, float time) const
{
Vector3 temp = r.o - center;
double a = Dot(r.d, r.d);
double b = 2 * Dot(r.d, temp);
double c = Dot(temp, temp) - radius*radius;
double discriminant = b*b - 4 * a*c;
if (discriminant > 0)
{
discriminant = sqrt(discriminant);
double t = (-b - discriminant) / (2 * a);
if (t < tmin)
t = (-b + discriminant) / (2 * a);
if (t<tmin || t>tmax)
return false;
return true;
}
return false;
}