views:

280

answers:

2

Hi everyone, I'm using gluUnProject to cast a ray into the scene and adding a primitive there. What I'm trying to do is now accurately pick existing primitives, so if I have 3 spheres I could click on one to delete it.

I think the solution would somehow check if the ray intersected with an object and check if its the closest to the casting origin. My solution so far is primitive and surrounds all objects with a bounding cube, is there anyway to simply to do this accurately for say spheres using:

does the ray intersect with ( object)

or

returnRayIntersections(ray);

Last thing, I'm using OpenGL with GLUT.

Thanks everyone, Laurence

+3  A: 

Using OpenGL selection mode is the best way to do this, since it can handle arbitrarily complex rendering, not just spheres. You can see many tutorials for this, but roughly: you start by setting GL in selection mode:

glRenderMode (GL_SELECT);

Then, you draw the scene, after setting up a selection buffer that captures the names of the fragments that you are rendering. This article will get you started.

Nehe's tutorial is long, but very good too.

Tarydon
+1  A: 

Another good way to implement picking in OpenGL is like this:

Draw your scene into the back buffer, using a unique color for each primitive that you want to select. If you are using a 24 bit mode, the colors can simply be #000001, #000002 etc. Turn off lighting, fog etc so that the colors you specify are the exact colors the pixels are going to take.

Don't blit the back-buffer to the screen (don't use glSwapBuffers). Instead, use glReadPixels to read the GL back-buffer into a memory buffer. After this you have a memory bitmap that you can read a pixel value from, corresponding to the location of the mouse on-screen. The color value you read out from this can easily then be mapped to the primitive (since it's going to be #000001, #000002 etc).

Here's some more information on this style of selection. This is what I like to use, since it has one advantage over the GL_SELECTION mode. If the 3D scene is unchanging and the mouse is being moved over it, I can get one copy of the back-buffer and then quickly estimate which entity is under the mouse, by simply referencing the appropriate pixel in my memory bitmap. I don't have to use any GL calls at all until the scene changes. Since my application has a lot of mouse hovering over a 3D scene and I need to quickly know which entity the mouse is floating over, I found this method really fast.

Tarydon
Aha this method looks great, found a great tutorial here: http://www.lighthouse3d.com/opengl/picking/index.php3?color1
Laurence Dawson
Little follow up, this works great!
Laurence Dawson