-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRay.cpp
89 lines (72 loc) · 1.67 KB
/
Ray.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
79
80
81
82
83
84
85
86
#include <iostream>
#include "Ray.h"
#include "Point3D.h"
#include "Vector3D.h"
Ray::Ray()
{
}
Ray::Ray(const Ray& ray)
: origin(ray.origin), direction(ray.direction)
{
direction.normalize();
}
Ray::Ray(const Point3D& origin, Vector3D& direction)
: origin(origin), direction(direction)
{
direction.normalize();
}
Ray::Ray(const Point3D& origin, const Point3D& dir)
: origin(origin), direction(dir - origin)
{
direction.normalize();
}
Ray& Ray::operator=(const Ray& ray)
{
origin = ray.origin;
direction = ray.direction;
return *this;
}
std::ostream& operator<<(std::ostream& os, const Ray& ray)
{
os << "Ray:: origin=" << ray.origin << " direction=" << ray.direction;
return os;
}
Point3D Ray::getOrigin() const
{
return origin;
}
Vector3D Ray::getDirection() const
{
return direction;
}
Point3D Ray::getPointAt(float t) const
{
return origin + (direction * t);
}
Ray Ray::getReflectedRay(const Point3D& p, const Vector3D& normal) const
{
float cosAlpha = -(DotProduct(direction, normal));
Vector3D reflectionDir = direction + normal * cosAlpha * 2;
return Ray(p, reflectionDir);
}
Ray Ray::getRefractedRay(const Point3D& p, const Vector3D& normal, float ior) const
{
float n = 1 / ior;
Vector3D norm = normal;
//if alpha is negative you are inside the object
float cosAlpha = -(DotProduct(direction, norm));
if (cosAlpha < 0)
{
norm = norm * (-1);
cosAlpha = -cosAlpha;
n = 1 / n;
}
//if discriminant is negative ray will be reflected
float discr = 1 - (1 - cosAlpha * cosAlpha) * (n * n);
if (discr < 0)
{
return getReflectedRay(p, norm);
}
Vector3D refractionDir = (direction * n) + norm * (cosAlpha * n - sqrt(discr));
return Ray(p, refractionDir);
}