I am implementing a UI library, and I want to implement pixel-perfect hit detection.
For example, if a UI element is a red ellipse, when I click on a red pixel, I want a click event to be emitted; otherwise, no event should be emitted.
I wonder how I can implement this pixel perfect hit-detection without a heavy performance cost.
The somewhat naive approach would be to render the id of the UI element onto a stencil attachment of some frame buffer. Then, every frame, I can read the pixel value of the texel my mouse is currently hovering on using glReadPixels.
The problem is that glReadPixels is synchronous and therefore blocking; it will halt the CPU execution until the frame is ready, perform the read operation and only then continue.
This is a potential performance bottleneck that I need to avoid.
What are my options?