Introduction

This sample demonstrates a way to select 3d objects from a scene using the mouse. In OpenGL nomenclature, this process is called "picking".

Controls

Press Esc or click the close button to exit.
The mouse pointer picks items automatically. Move the mouse to pick a different item.

Implementation

Every object in the scene is assigned a unique id by "coloring" all of its vertices with the same color. The color is generated by encoding the Int32 id into a 4-byte Rgba value.

A first rendering pass clears the screen to Int32.MaxValue, disables all textures and shaders and renders the scene using the aforementioned coloring scheme. As soon as this rendering is complete, we use GL.ReadPixels() to retrieve the pixel below the mouse cursor. By reversing the encoding process, we convert the Rgba value of the pixel back into the unique Int32 id.

A second rendering pass clears the screen once more and proceeds to render the scene normally (using all necessary textures and shaders). The user never sees the results of the first rendering pass!