-
Notifications
You must be signed in to change notification settings - Fork 0
/
UVSphere.cpp
79 lines (62 loc) · 1.77 KB
/
UVSphere.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
69
70
71
72
73
74
75
76
77
78
#include "UVSphere.h"
UVSphere::UVSphere(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 UVSphere::Hit(const Ray &r, float tmin, float tmax, float time, HitRecord &rec) 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.0*a*c;
if (discriminant > 0.0)
{
discriminant = sqrt(discriminant);
double t = (-b - discriminant) / (2.0*a);
if (t < tmin)
t = (-b + discriminant) / (2.0*a);
if (t<tmin || t>tmax)
return false;
rec.t = t;
rec.pos = r.o + t*r.d;
Vector3 n = /*rec.normal =*/ (rec.pos - center) / radius;
rec.uvw.InitFromW(n);
float twopi = 6.28318530718f;
float pi = 3.1415926535f;
float theta = acos(n.z);
float phi = atan2(n.y, n.x);
if (phi < 0.0f) phi += twopi;
float one_over_2pi = .159154943092f;
float one_over_pi = .318309886184f;
rec.uv = Vector2(phi*one_over_2pi, (pi - theta)*one_over_pi);
rec.material = material;
return true;
}
return false;
}
bool UVSphere::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;
}