Tuesday, September 19, 2017

How to Process Mouse Events in a 3D Scene, Part 3

3. Copy the Object ID buffer into local program memory to work with.

First, your program must allocate an array to hold the ID of the object underneath each pixel:

GLuint *data;
data = new GLuint[windowDimensions.x * windowDimensions.y];

Then, after drawing the scene each frame, copy the values in the Object ID color buffer to this array.  While glBindFramebuffer selects which framebuffer we read from during reading operations, the glReadBuffer function selects which attachment within that framebuffer to read from.

glReadPixels(0, 0, windowDimensions.x, windowDimensions.y, GL_RED_INTEGER, GL_UNSIGNED_INT, data);

Here we set the read buffer to our ObjectID color buffer, copy the object IDs into our data array, and then set the read buffer back to the original color attachment so that we can blit to the default framebuffer.


Now, when a mouse event comes in we can easily discover what object was clicked on.

auto handleMouseClick = [windowDimensions, &data](int x, int y, int mouseButton) {
    unsigned int objectID = data[x + y * windowDimensions.x];

Until next time!

Part 1
Part 2

No comments:

Post a Comment