Hello, this is driving me crazy, mainly because it's close but not quite
there.
I'm trying to set the fragment depth when I have a 3D position and a
camera position,basically what I get from ray-tracing.
Here's my perspective transform:-
void TerrainManager::Perspective(GLfloat fovy, GLfloat aspect, GLfloat
zNear, GLfloat zFar)
{
GLfloat xmin, xmax, ymin, ymax;
float an = tanf(fovy * PI/ 360.0f);
ymax = zNear * an;
ymin = -ymax;
xmax = ymax * aspect;
xmin = ymin * aspect;
float width = xmax - xmin;
float height = ymax - ymin;
float depth = zFar - zNear;
float q = -(zFar + zNear) / depth;
float qn = -(2.0f * zFar * zNear) / depth;
float w = 2.0f * zNear / width;
float h = 2.0f * zNear / height;
memset((void*)&projectionMatrix, 0, sizeof(mat4));
projectionMatrix[0].x = w;
projectionMatrix[1].y = h;
projectionMatrix[2].z = q;
projectionMatrix[2].w = -1.0;
projectionMatrix[3].z = qn;
// LOOK ===> projAB contains the vec2 that goes to the shader to do
the transform...
projAB.x = (zFar+zNear)/depth;
projAB.y = -(2.0f*zFar*zNear)/depth;
}
To get the real distance from the camera in the shader I use:-
distance = length(position3D - cameraPos);
gl_FragDepth = (projAB.y / distance) + projAB.x;
The value seems slightly off, and I can't work out if it's the near
plane not being included properlyor the aspect ratio or whatever, but
it's SO close it's really annoying. I could use the projection matrix
but this seems a quicker method.
I've used information from here, but I guess it's wrong some how?:-
http://www.iquilezles.org/www/articles/raypolys/raypolys.htm
I noticed that my projAB.y is negative compared to that web example, but
thatway it shows OK. That's why I've included my perspective transform
in case there's a problem with that directly.
Can any one help?
Thanks,
Dave.