00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012 #ifndef _CELMATH_INTERSECT_H_
00013 #define _CELMATH_INTERSECT_H_
00014
00015 #include "ray.h"
00016 #include "sphere.h"
00017 #include "ellipsoid.h"
00018
00019
00020 template<class T> bool testIntersection(const Ray3<T>& ray,
00021 const Sphere<T>& sphere,
00022 T& distance)
00023 {
00024 Vector3<T> diff = ray.origin - sphere.center;
00025 T s = (T) 1.0 / square(sphere.radius);
00026 T a = ray.direction * ray.direction * s;
00027 T b = ray.direction * diff * s;
00028 T c = diff * diff * s - (T) 1.0;
00029 T disc = b * b - a * c;
00030 if (disc < 0.0)
00031 return false;
00032
00033 disc = (T) sqrt(disc);
00034 T sol0 = (-b + disc) / a;
00035 T sol1 = (-b - disc) / a;
00036
00037 if (sol0 > 0)
00038 {
00039 if (sol0 < sol1 || sol1 < 0)
00040 distance = sol0;
00041 else
00042 distance = sol1;
00043 return true;
00044 }
00045 else if (sol1 > 0)
00046 {
00047 distance = sol1;
00048 return true;
00049 }
00050 else
00051 {
00052 return false;
00053 }
00054 }
00055
00056
00057 template<class T> bool testIntersection(const Ray3<T>& ray,
00058 const Ellipsoid<T>& e,
00059 T& distance)
00060 {
00061 Vector3<T> diff = ray.origin - e.center;
00062 Vector3<T> s((T) 1.0 / square(e.axes.x),
00063 (T) 1.0 / square(e.axes.y),
00064 (T) 1.0 / square(e.axes.z));
00065 Vector3<T> sdir(ray.direction.x * s.x,
00066 ray.direction.y * s.y,
00067 ray.direction.z * s.z);
00068 Vector3<T> sdiff(diff.x * s.x, diff.y * s.y, diff.z * s.z);
00069 T a = ray.direction * sdir;
00070 T b = ray.direction * sdiff;
00071 T c = diff * sdiff - (T) 1.0;
00072 T disc = b * b - a * c;
00073 if (disc < 0.0)
00074 return false;
00075
00076 disc = (T) sqrt(disc);
00077 T sol0 = (-b + disc) / a;
00078 T sol1 = (-b - disc) / a;
00079
00080 if (sol0 > 0)
00081 {
00082 if (sol0 < sol1 || sol1 < 0)
00083 distance = sol0;
00084 else
00085 distance = sol1;
00086 return true;
00087 }
00088 else if (sol1 > 0)
00089 {
00090 distance = sol1;
00091 return true;
00092 }
00093 else
00094 {
00095 return false;
00096 }
00097 }
00098
00099 #endif // _CELMATH_INTERSECT_H_