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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| #include <iostream>
#include <algorithm>
using std::cout;
using std::endl;
struct Vec3f {
float x, y, z;
Vec3f() { }
Vec3f(float, float, float) { }
};
struct Ray {
Ray(Vec3f const&, Vec3f const&) { }
int sign[42];
Vec3f origin;
Vec3f inv_direction;
};
class Box {
public:
Box();
Box(const Vec3f &mini, const Vec3f &maxi);
bool intersect(Ray const &r, float t0, float t1) const;
void expand(Box box);
protected:
Vec3f bounds[2];
};
Box::Box(const Vec3f &mini, const Vec3f &maxi) {
bounds[0] = mini;
bounds[1] = maxi;
}
void Box::expand(Box box) {
bounds[0] = Vec3f(std::min(box.bounds[0].x, bounds[0].x), std::min(box.bounds[0].x, bounds[0].x), std::min(box.bounds[0].x, bounds[0].x));
bounds[1] = Vec3f(std::max(box.bounds[0].x, bounds[0].x), std::max(box.bounds[0].x, bounds[0].x), std::max(box.bounds[0].x, bounds[0].x));
}
bool Box::intersect(Ray const &r, float t0, float t1) const {
float tmin, tmax, tymin, tymax, tzmin, tzmax;
tmin = (bounds[r.sign[0]].x - r.origin.x) * r.inv_direction.x;
tmax = (bounds[1 - r.sign[0]].x - r.origin.x) * r.inv_direction.x;
tymin = (bounds[r.sign[1]].y - r.origin.y) * r.inv_direction.y;
tymax = (bounds[1 - r.sign[1]].y - r.origin.y) * r.inv_direction.y;
if ((tmin > tymax) || (tymin > tmax))
return false;
if (tymin > tmin)
tmin = tymin;
if (tymax < tmax)
tmax = tymax;
tzmin = (bounds[r.sign[2]].z - r.origin.z) * r.inv_direction.z;
tzmax = (bounds[1 - r.sign[2]].z - r.origin.z) * r.inv_direction.z;
if ((tmin > tzmax) || (tzmin > tmax))
return false;
if (tzmin > tmin)
tmin = tzmin;
if (tzmax < tmax)
tmax = tzmax;
return ((tmin < t1) && (tmax > t0));
return false;
}
int main(int argc, char **argv)
{
Vec3f mini(1, 1, 1);
Vec3f maxi(2, 2, 2);
Box b(mini, maxi);
Vec3f o(1.5, 1.5, 0);
Vec3f d(0, 0, 1);
Ray r(o, d);
if (b.intersect(r, 0, 4))
cout << "interstion ok" << endl;
else
cout << "nok" << endl;
system("pause");
return 0;
} |
Partager