Getting the distance to a 3D object from a depth texture shouldn't be too difficult. The steps to create a depth texture are, enable Depth Testing, bind the depth texture for rendering, perform your operations on (or using data from) the depth texture.
This is how you create a depth texture in OpenGL:GLuint id; int width = 512; int height = 512; // create a depth texture glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); glTexImage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); // set some parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); // unbind
To use the depth texture within your shaders is the exact same way as you would any other texture, bind it to a texture slot and set a uniform for it. Make sure you also have enabled depth testing.
glUniform1i(glGetUniformLocation(shaderProgram, "DepthTexture"), 1);
Within your shader you can access it like so:
uniform sampler2D DepthTexture;
When you sample your depth texture within a shader the Z component will store the depth of the fragment. i.e:
float depth = texture(DepthTexture, UV).z
You might want to bind the depth texture to a Framebuffer, but that is exactly the same as attaching any other texture apart from you need to use 'GL_DEPTH_ATTACHMENT' rather than something like 'GL_COLOR_ATTACHMENT0'.
Thanks! But how to calculate distance from camera eye to the pixel of the depth? And what if I use logarithm z ? Is it not matter?