What are the fastest ways to read certain texels from a texture into CPU?

Hello,
I’m coding an app that uses OpenGL to render some textures from a 3D model (normals, depth,…)
Then I want to read vertex information that verify a certain condition. So I can’t know how many texels I’m gonna retrieve and it changes with the camera view of the object.
Using glReadPixels and glGetTexImage are expensive since I’ll have to retrieve the whole texture and then select texels on CPU.
I’m looking for a faster way to get only the information I need. A cross platform solution would be more appreciated.

glReadPixels can retrieve an arbitrary rectangle from the framebuffer. glGetTextureSubImage (requires OpenGL 4.5) can do likewise for a texture.

If you want to read scattered pixels, you can use a shader to sample the texture and store the results in a SSBO or image.

Either way, any form of read-back risks synchronisation; any function which copies data from the GPU to the CPU will block until the GPU has finished executing any commands which could modify that data. You can use glFenceSync() to create a fence object whose status can be queried with glGetSync().

But when generating the SSBO you have to specify a size and I don’t know how many pixels I’m going to retrieve.

Then estimate an upper bound; if that turns out not to be enough, double it and repeat the process.