-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sphere.cpp
54 lines (46 loc) · 1.09 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
/*----------------------------------------------------------
* COSC363 Ray Tracer
*
* The sphere class
* This is a subclass of Object, and hence implements the
* methods intersect() and normal().
-------------------------------------------------------------*/
#include "Sphere.h"
#include <math.h>
/**
* Sphere's intersection method. The input is a ray (pos, dir).
*/
float Sphere::intersect(Vector pos, Vector dir)
{
Vector vdif = pos - center;
float b = dir.dot(vdif);
float len = vdif.length();
float c = len*len - radius*radius;
float delta = b*b - c;
if(fabs(delta) < 0.001)
return -1.0;
if(delta < 0.0)
return -1.0;
float t1 = -b - sqrt(delta);
float t2 = -b + sqrt(delta);
if(fabs(t1) < 0.001 )
{
if (t2 > 0)
return t2;
else
t1 = -1.0;
}
if(fabs(t2) < 0.001 )
t2 = -1.0;
return (t1 < t2)? t1: t2;
}
/**
* Returns the unit normal vector at a given point.
* Assumption: The input point p lies on the sphere.
*/
Vector Sphere::normal(Vector p)
{
Vector n = p - center;
n.normalise();
return n;
}