A 3D Object Picking Technique that Uses OpenGL

Friday Apr 4th 2003 by Andy McGovern
Share:

How to set up a 3D model in OpenGL so that a user can pick and identify objects in the model. This technique is very helpful in both game programming and visualization.

Environment: VC++6, Win32

Overview

This article demonstrates a simple technique for capturing which 3D object the user clicked on with the mouse. Of course, it can be used to discover the object at any X,Y position on the screen. The most difficult thing about picking is telling OpenGL to send its output directly to an image; and that technique was covered on a previous CodeGuru article; it's available for viewing here. Once you are able to send graphics directly to an image (DIB Section) the rest is trivial.

Here is an outline of the basic approach:

  1. The user clicks the mouse (or some input device). Capture the X and Y position of the click.
  2. Now, set up a lookup table of colors: 1 color for each 3D object in the model.
  3. Re-draw the model, but instead of the normal colors, use the colors from the lookup table. And one more thing, don't display the output image on the screen.
  4. Find the color of the image pixel at the X-Y position of the click and use the color to find the corresponding 3D object in the lookup table.
  5. Re-build your model using original colors and textures.

This simple technique is called the Painter's Algorithm. It's nice because there is no complicated geometry. Its downfall is that it is not the most efficient approach because of the necessity of redrawing the entire model, at least the parts that may be picked. However, some steps can be taken to improve the efficiency of Step 3 by keeping in mind that the user will never see the intermediate model, so the resolution may be lower than the original model. For example, in the sample project the spheres are broken into triangles, but for the intermediate "pick" image you may use far fewer triangles to describe the sphere, thus making the drawing code much faster.

Sample Project

Use the left mouse button to rotate the solar system and the RIGHT mouse button to select a planet.

Enjoy.

Downloads

Download demo project - 405 Kb

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved