Triangle.cc

Go to the documentation of this file.
00001 
00004 #include "BoundingBox.h"
00005 #include "Triangle.h"
00006 #include "HitRecord.h"
00007 #include "Math.h"
00008 #include "Ray.h"
00009 #include <iostream>
00010 #include <stdlib.h>
00011 using namespace std;
00012 
00017 Triangle::Triangle(Material* material, const Point &A, const Point &B, const Point &C)
00018     : Primitive(material), a(A), b(B), c(C)
00019 {
00020 }
00021 
00025 Triangle::~Triangle()
00026 {
00027 }
00028 
00029 
00037 void Triangle::intersect(HitRecord& hit, const RenderContext& context, const Ray& ray) const
00038 {
00039     Vector edge1, edge2, tvec, pvec, qvec;
00040 
00041     double det, inv_det, u, v, t;
00042 
00043     /* find vectors for two edges sharing vert0 */
00044     edge1 = b - a;
00045     edge2 = c - a;
00046 
00047    /* begin calculating determinant - also used to calculate U parameter */
00048     pvec = Cross(ray.direction(), edge2);
00049 
00050     /* if determinant is near zero, ray lies in plane of triangle */
00051     det = Dot(edge1, pvec);
00052 
00053    if (det > -EPSILON && det < EPSILON)
00054        return;
00055 
00056    inv_det = 1.0 / det;
00057 
00058    /* calculate distance from vert0 to ray origin */
00059    tvec = ray.origin() - a;
00060 
00061    /* calculate U parameter and test bounds */
00062    u = Dot(tvec, pvec) * inv_det;
00063    if (u < 0.0 || u > 1.0)
00064        return;
00065 
00066    /* prepare to test V parameter */
00067    qvec = Cross(tvec, edge1);
00068 
00069    /* calculate V parameter and test bounds */
00070    v = Dot(ray.direction(), qvec) * inv_det;
00071    if (v < 0.0 || u + v > 1.0)
00072        return;
00073 
00074    /* calculate t, ray intersects triangle */
00075    t = Dot(edge2, qvec) * inv_det;
00076 
00077    if (hit.hit(t, this, matl)) {
00078        // probably want to stash u and v
00079    }
00080 }
00081 
00082 
00086 void Triangle::normal(Vector& normal, const RenderContext&,
00087                       const Point&, const Ray&, const HitRecord&) const
00088 {
00089 
00090     Vector edge1, edge2;
00091 
00092     edge1 = b - a;
00093     edge2 = c - a;
00094 
00095     normal = Cross(edge1, edge2);
00096     normal.normalize();
00097 }
00098 
00099 
00103 void Triangle::getBounds(BoundingBox& bbox) const
00104 {
00105     bbox.extend(a);
00106     bbox.extend(b);
00107     bbox.extend(c);
00108 }
00109 

Generated on Tue Jan 29 21:34:54 2008 for specter by  doxygen 1.4.6