If your GPU card has OpenGL 4.2, you may use the function imageStore()
in GLSL to mark the triangle Id in an image. In my case, I need to detect all triangles behind a predefined window on the screen. Picking (choosing rendered triangles on a window) works similarly. The selection runs in real-time for me.
The maximum size of an image (or texture) should >= 8192x8192 = 64 M. So it can be used up to 64 M primitives (and even more if we use 2, 3 images).
Saving all trianges Id behind the screen could be done with this fragment shader:
uniform uimage2D id_image;
void main()
{
color_f = vec4(0)
ivec2 p;
p.x = gl_PrimitiveID % 2048;
p.y = gl_PrimitiveID / 2048;
imageStore(id_image, p, uvec4(255));
}
To save all trianges Id rendered on the screen: first, we precompute a depth buffer, then use a slightly different fragment shader:
uniform uimage2D id_image;
**layout(early_fragment_tests) in;** //the shader does not run for fragment > depth
void main()
{
color_f = vec4(0)
ivec2 p;
p.x = gl_PrimitiveID % 2048;
p.y = gl_PrimitiveID / 2048;
imageStore(id_image, p, uvec4(255));
}