Pixelwise occlusion detection in Opengl


My problem is that I have a triangle mesh and a camera position.
I would like to draw the triangle indices onto a image rendered by the camera position, therefore I got an image with each pixel indicate the visible triangle index.
I know how to do this in CPU with a bounding volume hierarchy, e.g. cast a ray for each pixel of the camera and intersect with the triangle mesh, but this is too slow for my application.

So an intuitive idea is to do this in an offscreen rendering. But I have no idea how to add triangle indices into vertex buffer and have no idea how to draw the indices onto the frame buffer with the indices.

Is it possible to do in opengl? If possible, please enlighten me a little how to do it?



Create a framebuffer object with an integer-format (e.g. GL_R32I) texture for the colour buffer. The vertex shader only needs to set gl_Position. The fragment shader is just e.g.

out int output;
void main() {
    output  = gl_PrimitiveID;