Hello!
I’ve recently started work on a game engine, but I’ve run into a slight hiccup - I cannot get my fragment shader to read a depth texture. Just to be clear, the fragment shader can read from color textures and the depth texture itself is working - I verified that with glReadPixels - but the fragmentShader just won’t read the depth data.
Setup:
I have one FBO, fbo that I use for my first pass. I then want to visualize the data in fbo.depthTexture by drawing it on screen.
Here is the revelant code:
Main Game Loop:
// Draw my original scene (consisting of one model) to fbo.
fbo.bind();
shader.bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
model.render();
// Unbind fbo (bind default fbo, ie, screen) and draw the fbo.depthTexture.
fbo.unbind();
fullscreenQuadTexturedShader.bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
fullscreenQuadTexturedShader.setInt("tex", 0);
// Uncommenting the next line would bind the 0th (first) color attachment at GL_TEXTURE0.
// fbo.bindColorTexture(0, 0);
fbo.bindDepthTexture(0); // Bind the depthTexture to GL_TEXTURE0
sqMesh.render();
// Debugging code
fbo.bind();
ByteBuffer buffer = BufferUtils.createByteBuffer(display.getWidth() * display.getHeight());
glReadPixels(0, 0, display.getWidth(), display.getHeight(), GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, buffer);
for (int i = 0; i < display.getWidth() * display.getHeight(); i++) {
int depth = Byte.toUnsignedInt(buffer.get(i)); // This works perfectly.
}
Fragment Shader:
#version 330
in vec2 fsTexCoord;
out vec3 finalColor;
uniform sampler2D tex;
void main()
{
vec4 texColor = texture(tex, fsTexCoord);
finalColor = texColor.rrr;
}
Relevant FBO functions:
public FBO attachDepthTexture() {
depthTextureId = glGenTextures();
glBindTexture(GL_TEXTURE_2D, depthTextureId);
// I've also tried GL_DEPTH_STENCIL with GL_DEPTH_STENCIL and GL_UNSIGNED_INT_24_8, but got the same results.
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
// Added for experimentation
// glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTextureId, 0);
glBindTexture(GL_TEXTURE_2D, 0);
return this;
}
public void bindDepthTexture(int location) {
glActiveTexture(GL_TEXTURE0 + location);
glBindTexture(GL_TEXTURE_2D, depthTextureId);
}
As mentioned above, replacing bindDepthTexture with bindColorTexture gives the expected result, and so does the glReadPixels at the end. Any tips on what I’m missing would be appreciated!
P.S. I’m aware that this question has been asked all too often on this forum and I’ve gone through them all, and yet I cannot figure out what the problem is.