-
Notifications
You must be signed in to change notification settings - Fork 0
/
geometries.cpp
93 lines (69 loc) · 1.79 KB
/
geometries.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
87
88
89
90
91
92
/*
* @file: geometries.cpp
* @author: Ondrej Hirjak, 2009
* @description:
*/
#include "V2Base.h"
#include "colors.h"
#include "geometries.h"
Vector3D Vector3D::Normalize() const
{
Vector3D vec;
double length = x * x + y * y + z * z;
length = sqrt(length);
vec.x = x / length;
vec.y = y / length;
vec.z = z / length;
return vec;
}
Vector3D Vector3D::operator +(Vector3D p)
{
return Vector3D(x + p.x, y + p.y, z + p.z);
}
Vector3D Vector3D::operator -(Vector3D p)
{
return Vector3D(x - p.x, y - p.y, z - p.z);
}
Vector3D Vector3D::operator *(double t)
{
return Vector3D(x * t, y * t, z * t);
}
double Sphere::RayIntersect(Ray &ray, IntersectData *intersectData)
{
double A = 1.0; // normalized ray vector
double B = 2.0 * (ray.Vector().x * (ray.Point().x - center.x) + ray.Vector().y * (ray.Point().y - center.y) + ray.Vector().z * (ray.Point().z - center.z));
double C = pow(ray.Point().x - center.x, 2.0) + pow(ray.Point().y - center.y, 2.0) + pow(ray.Point().z - center.z, 2.0) - radius * radius;
double Det = B * B - 4.0 * A * C;
if (Det >= 0.0)
{
double t = (-B - sqrt(Det)) / 2;
if (t > 0.0)
{
if (intersectData)
{
Point3D contact = (Vector3D)ray.Point() + ray.Vector() * t;
Vector3D normal = (Vector3D)contact - center;
normal = normal.Normalize();
intersectData->contact = contact;
intersectData->normal = normal;
intersectData->color = color;
}
return t;
}
t = (-B + sqrt(Det)) / 2;
if (t > 0.0)
{
if (intersectData)
{
Point3D contact = (Vector3D)ray.Point() + ray.Vector() * t;
Vector3D normal = (Vector3D)contact - center;
normal = normal.Normalize();
intersectData->contact = contact;
intersectData->normal = normal;
intersectData->color = color;
return t;
}
}
}
return INFINITY;
}