// *********************************************************
// Object Class
// Author : Tamy Boubekeur (boubek@gmail.com).
// Copyright (C) 2010 Tamy Boubekeur.
// All rights reserved.
// *********************************************************

#include "Object.h"
#include "Triangle.h"
#include "Vertex.h"
#include "Scene.h"
#include <stdio.h>

using namespace std;

bool Object::intersect(const Ray& r, IntersectedTriangle& tri) const
{
    //*
    return mesh.getTree().intersect(r, tri);
    /*/
    // Brute force
    Vec3Df res;
    if(!r.intersect(getBoundingBox(),res)) return false;
    const std::vector<Triangle>& tris = mesh.getTriangles();
    const std::vector<Vertex>& verts = mesh.getVertices();
    float u = 0.0f, v = 0.0f, tt = 0.0f; // unused
    float dist = -1.0f;

    for(unsigned int t = 0; t < tris.size(); t++)
        if(r.intersect(verts[tris[t].getVertex(0)].getPos(),
                       verts[tris[t].getVertex(1)].getPos(),
                       verts[tris[t].getVertex(2)].getPos(),
                       res, u, v, tt))
        {
            float d = r.getT(res);
            if(dist < 0.0f || d < dist)
            {
                dist = d;
                ipoint = res;
                uF = u;
                vF = v;
                iTriangle = tris[t];
            }
        }

    return dist >= 0.0f;
    //*/
}

bool Object::intersectWithTransform(const Ray& r, IntersectedTriangle& tri) const
{
	IntersectedTriangle tmp;
	Ray r2 = r;
	r2.setOrigin(r.getOrigin() - trans);
	if(intersect(r2, tmp))
	{
		tri = tmp;
		tri.point += trans;
		return true;
	}
	else
		return false;
}
