I have a ray box intersection algorithm that is supposedly returning the distance to the intersected plane, however it is not meeting my expectaions.
I am outputing the absolute value of the position of the intersection point as a color. My expectation being that the color should be the same wherever the camera is, since the intersection point hasn't moved.
However my cube has different colors depending on where it is looked from:
Front view:
Slightly uo and right view (same face):
As you can see the color has changed based on the position.
I am raytracing the entire structure on teh fragment shader as follows:
#version 430
in vec2 f_coord;
out vec4 fragment_color;
uniform vec3 camera_pos;
uniform float aspect_ratio;
uniform float cube_dim;
#define EPSILON 0.0001
// Check whether the position is inside of the specified box
bool inBoxBounds(vec3 corner, float size, vec3 position)
{
bool inside = true;
//Put the position in the coordinate frame of the box
position-=corner;
//The point is inside only if all of it's components are inside
for(int i=0; i<3; i++)
{
inside = inside && (position[i] > -EPSILON);
inside = inside && (position[i] < size+EPSILON);
}
return inside;
}
//Calculate the distance to the intersection to a box, or inifnity if the bos cannot be hit
float boxIntersection(vec3 origin, vec3 dir, vec3 corner0, float size)
{
dir = normalize(dir);
//calculate opposite corner
vec3 corner1 = corner0 + vec3(size,size,size);
//Set the ray plane intersections
float coeffs[6];
coeffs[0] = (corner0.x - origin.x)/(dir.x);
coeffs[1] = (corner0.y - origin.y)/(dir.y);
coeffs[2] = (corner0.z - origin.z)/(dir.z);
coeffs[3] = (corner1.x - origin.x)/(dir.x);
coeffs[4] = (corner1.y - origin.y)/(dir.y);
coeffs[5] = (corner1.z - origin.z)/(dir.z);
float t = 1.f/0.f;
//Check for the smallest valid intersection distance
for(uint i=0; i<6; i++)
t = coeffs[i]>=0&& inBoxBounds(corner0,size,origin+dir*coeffs[i])?
min(coeffs[i],t) : t;
return t;
}
void main()
{
vec3 r = vec3(f_coord.x, f_coord.y, 1.f/tan(radians(40)));
vec3 dir = r;
dir.y /= aspect_ratio;
r = camera_pos;
float t = boxIntersection(r, dir, vec3(-cube_dim), cube_dim*2);
if(isinf(t))
discard;
r += dir*(t);
fragment_color = vec4(abs(r)/100,0);
}
Edit:
f_coord is the normalized coordinate system from -1 to 1 (the normalized screen coordinate in the opengl window)
camera_pos is the position of the camera in the 3D world coordinate system.