I am trying to develop a simple ray tracer and got the sphere, plane and cone right but I am facing an issue I can't wrap my head around. I tried several different formulas for the infinite cylinder and all those who are supposed to take rotation into account makes it "degenerate" when using a rotation that's not 0 or 1 and on only one axis... For instance :
0,0,1 works but 0,0,0.5 gives me an ellipsoid sphere and 0,1,1 gives me an hyperboloid...
Here is the the code I am using to intersect the ray with the cylinder.
enum e_bool test_intersect(double t[2], double *current_z)
{
enum e_bool retvalue;
retvalue = false;
if ((t[0] > DOUBLE_ZERO)
&& (t[0] < *(current_z) || double_equal(*(current_z), t[0])))
{
*(current_z) = t[0];
retvalue = true;
}
if (!double_equal(t[0], t[1])
&& (t[1] > DOUBLE_ZERO)
&& (t[1] < *(current_z) || double_equal(*(current_z), t[1])))
{
*(current_z) = t[1];
retvalue = true;
}
return (retvalue);
}
enum e_bool intersect_cylinder(t_primitive cp, t_ray r, double *current_z)
{
t_vec3 eye = vec3_substract(r.origin, cp.position);
double a = vec3_dot(r.direction, r.direction) - pow(vec3_dot(r.direction, cp.direction), 2);
double b = 2 * (vec3_dot(r.direction, eye) - vec3_dot(r.direction, cp.direction) * vec3_dot(eye, cp.direction));
double c = vec3_dot(eye, eye) - pow(vec3_dot(eye, cp.direction), 2) - cp.radius * cp.radius;
double t[2];
double delta;
delta = sqrt((b * b) - (4.0 * a * c));
if (delta < 0)
return (false);
t[0] = (-b - (delta)) / (2.0 * a);
t[1] = (-b + (delta)) / (2.0 * a);
return (test_intersect(t, current_z));
}
Here is the cylinder with a rotation of 1, 0, 0
Here it is with a rotation of 1, 1, 0
What am I missing, the issue is the same with perspective or isometric ray casting, so it has to do with the intersection algorithm, but I can't find what is wrong...
I found the solution to my issue, after reading these pages (gamedev helped me a lot) :
http://mrl.nyu.edu/~dzorin/cg05/lecture12.pdf
http://www.gamedev.net/topic/467789-raycylinder-intersection/
I re-did my intersection equation like so and it's working properly :
enum e_bool intersect_cylinder(t_primitive cp, t_ray r, double *current_z)
{
t_vec3 pdp = vec3_substract(cp.direction, cp.position);
t_vec3 eyexpdp = vec3_cross(vec3_substract(r.origin, cp.position), pdp);
t_vec3 rdxpdp = vec3_cross(r.direction, pdp);
float a = vec3_dot(rdxpdp, rdxpdp);
float b = 2 * vec3_dot(rdxpdp, eyexpdp);
float c = vec3_dot(eyexpdp, eyexpdp) - (cp.radius * cp.radius * vec3_dot(pdp, pdp));
double t[2];
double delta;
delta = sqrt((b * b) - (4.0 * a * c));
if (delta < 0)
return (false);
t[0] = (-b - (delta)) / (2.0 * a);
t[1] = (-b + (delta)) / (2.0 * a);
return (test_intersect(t, current_z));
}
Now my normals are wrong, but that's not that big of an issue to fix.