fart/shapes/Intersect.cc

112 lines
3.0 KiB
C++

#include "Intersect.h"
#include <iostream>
using namespace std;
Intersect::Intersect(const vector< refptr<Shape> > & shapes)
{
int num_shapes = shapes.size();
if (num_shapes > 2)
{
m_shape2 = shapes[num_shapes - 1];
vector< refptr<Shape> > rest = shapes;
rest.pop_back();
m_shape1 = new Intersect(rest);
}
else if (num_shapes == 2)
{
m_shape1 = shapes[0];
m_shape2 = shapes[1];
}
else
{
cerr << __FILE__ << ": " << __LINE__
<< ": error: Intersect::Intersect() called with only "
<< num_shapes
<< " sub-shapes!"
<< endl;
exit(4);
}
}
Shape::IntersectionList Intersect::intersect(refptr<Shape> _this, const Ray & ray)
{
Ray ray_inv = m_inverse.transform_ray(ray);
IntersectionList res1 = m_shape1->intersect(m_shape1, ray_inv);
if (res1.size() == 0) /* optimization */
return res1;
IntersectionList res2 = m_shape2->intersect(m_shape2, ray_inv);
BoolIntersectionList merged(res1, res2, ray_inv.getOrigin());
IntersectionList res;
bool in1 = false, in2 = false;
/* initially go through the merged intersections to see whether
* the ray started inside one of the sub-objects */
for (int i = 0, sz = merged.size(), saw1 = 0, saw2 = 0;
i < sz && (!saw1 || !saw2);
i++)
{
Vector normal = merged[i].intersection.normal;
double dot = - (ray_inv.getDirection() % normal);
bool back = dot < 0.0;
bool left = merged[i].left;
if (back)
{
if (left && !saw1)
in1 = true;
else if (!left && !saw2)
in2 = true;
}
if (left)
saw1 = 1;
else
saw2 = 1;
}
bool in_bool = in1 && in2;
for (int i = 0, sz = merged.size(); i < sz; i++)
{
Vector normal = merged[i].intersection.normal;
double dot = - (ray_inv.getDirection() % normal);
bool front = dot > 0.0;
bool left = merged[i].left;
if (front)
{
if (left)
in1 = true;
else
in2 = true;
if (!in_bool && in1 && in2)
{
/* we found an intersection point with the boolean object */
in_bool = true;
res.add( merged[i].intersection.transform(m_transform) );
}
}
else
{
if (in_bool && in1 && in2)
{
/* we found an intersection point with the boolean object */
res.add( merged[i].intersection.transform(m_transform) );
}
if (left)
in1 = false;
else
in2 = false;
in_bool = false;
}
}
return res;
}
refptr<Shape> Intersect::clone()
{
Intersect * s = new Intersect(*this);
s->m_shape1 = m_shape1->clone();
s->m_shape2 = m_shape2->clone();
return refptr<Shape>(s);
}