Talk:Mathematics of glTexGen

From OpenGL Wiki
Jump to: navigation, search

Don't know if this is the right place for writing this, but I was just applying the maths mentioned in the article for a project I was working on, and I found out the GL_SPHERE_MAP calculations are not correct, for where it says:

reflectionVector = myEyeVertex - myEyeNormal * 2.0 * dot3D(myEyeNormal, myEyeNormal);

It should be:

reflectionVector = myEyeVertex - myEyeNormal * 2.0 * dot3D(myEyeVertex, myEyeNormal);

And where it says:

m = 1.0 / 2.0 * sqrt(dot3D(reflectionVector, reflectionVector));

It should be:

m = 1.0 / ( 2.0 * sqrt(dot3D(reflectionVector, reflectionVector)) );

I'm not an expert on the subject, but having checked the OpenGL reference pages and looking carefully at the glTexGen documentation, it seems the original formula posted on this page was not correct.

Still incorrect

The calculations to replicate GL_SPHERE_MAP functionality still seem incorrect. Implementing the algorithm provided to create my texture coordinates, it does not look a thing like the effect that actually using the glTexGen render state with GL_SPHERE_MAP generates. This is most likely due to the fact that this example code, nor most example code I ever come across anywhere on the internet, never takes into consideration that the eye point could be somewhere else but the origin. There were also a few other issues, such as adding the 1.0f to the z of the relfectionVector needed to be subtracted instead, normalization of the verticies was not needed further scewing the texture on the surface, and the sphere map was coming out completely inverted and needed to be negated to fix it's incorrect orientation on the surface.

The following code works perfectly for me no matter where my camera and/or the mesh are being rendered in the coordinate system, and is the closest match to reproducing the look of glTexGen GL_SPHERE_MAP I've seen from trying may different sphere map algorithms:

 for(i=0; i<total; i++) {
   myEyeVertex = MatrixTimesVector(ModelviewMatrix, myVertex[i]);
   myEyeVertex.x -= ModelviewMatrix._41;
   myEyeVertex.y -= ModelviewMatrix._42;
   myEyeVertex.z -= ModelviewMatrix._43;
   myEyeNormal = Normalize(VectorTimesMatrix(myNormal[i], InverseModelviewMatrix));
   reflectionVector = myEyeVertex - myEyeNormal * 2.0 * dot3D(myEyeVertex, myEyeNormal);
   reflectionVector.z -= 1.0;
   m = 1.0 / (2.0 * sqrt(dot3D(reflectionVector, reflectionVector)));
   myTexCoord[i].s = -(reflectionVector.x * m + 0.5);
   myTexCoord[i].t = -(reflectionVector.y * m + 0.5);