Sign in to follow this  
yaazz

OpenGL Trying to get picking to work

Recommended Posts

yaazz    122
Hello, I am following this tutorial on picking http://gpwiki.org/index.php/OpenGL:Tutorials:Picking But can not seem to get it to work on a grid of squares. It doesn't matter where you click, it always says there was a hit. Does anyone see what im doing wronng? the only thing i changed was the perspective coordinates so that you can see all of the squares on the screen.
//
//Open GL picking Test
// 


#include <GL/glut.h>
#include <stdio.h> 
#include <stdlib.h>
#include <time.h>
#include <math.h> 

#define NUMSQUARES 64
#define WIDTH 10 
#define HEIGHT 10 
#define wWIDTH 320
#define wHEIGHT 240 

void list_hits(GLint hits, GLuint *names);
void mousedw(int x, int y, int but);
void list_hits(GLint hits, GLuint *names);
void gl_select(int x, int y);
void gl_selall(GLint hits, GLuint *buff);

//Strcut square and board represent the minesweeper field 
struct square 
{
  int x;
  int y; 	     // X and Y position of square		
  char letter; //state of square, i.e clicked, exploded, flagged, etc
  int r;
  int g;
  int b;
  int bombsAround;
  int isBomb; //is this a bomb square
  int mouseON; //is mouse on square
}; 

struct coord
{
  int worldX; //world coords from mouse
  int worldY; 
};
struct board
{
  int boardState; //state of board
  int width; //width of squares
  int height; //height of squares 
  struct square grid[NUMSQUARES]; //amount of squares
};
int R=100,G=100,B=100,elapsedTime=0; //RGB and timer values
int windowH=480,windowW=640; 
struct board gameGrid; 
struct coord C;

void createGrid(struct board* inGrid); 
void keyboard(unsigned char key, int x, int y); 

void mydisplay(); 
void mouseClick(int button, int state, int x, int y); 
void mousedw(int x, int y, int but);
void gl_select(int x, int y); 
void gl_selall(GLint hits, GLuint *buff); 
void list_hits(GLint hits, GLuint *names); 
void myReshape(int w, int h); 

int main(int argc, char** argv); 


//function to fill the Board struct with proper coordinates
void createGrid(struct board* inGrid) 
{
  inGrid->boardState=0;
  int i=0,tempx=0,tempy=0;
	 inGrid->grid[0].y=0;
	inGrid->grid[0].x=0; 
	inGrid->grid[0].letter='h'; 	  
	inGrid->grid[0].r=255;
        inGrid->grid[0].g=255;
        inGrid->grid[0].b=255;
	//printf("grid 0 x=%d y=%d letter=%c \n",inGrid->grid[0].x,inGrid->grid[0].y);
	for(i=1;i<64;i++)
	{
	  inGrid->grid[i].r=255;
	  inGrid->grid[i].g=255;
	  inGrid->grid[i].b=255;
		if(i%8==0) 
		{
			tempy+=inGrid->height+1;
			tempx=0-inGrid->width-1;
		}
		tempx+=inGrid->width+1; 
		inGrid->grid[i].x=tempx; 
		inGrid->grid[i].y=tempy; 
		inGrid->grid[i].letter='h';
		//	printf("grid %d x=%d y=%d letter=%c \n",i,inGrid->grid[i].x,inGrid->grid[i].y);
	}
}






//drawing function
void mydisplay(){

int i,x=0,y=0;
glClear(GL_COLOR_BUFFER_BIT); 

for(i=0;i<64;i++)
{
glLoadName(i); /* Overwrite the first name in the buffer */
glLoadIdentity();
	
glTranslated(gameGrid.grid[i].x,gameGrid.grid[i].y,0.0);	

glColor3ub(gameGrid.grid[i].r,gameGrid.grid[i].g,gameGrid.grid[i].b); 

//load the name on to the name stack
 glPushName(i);


//use grid square moved to be around the origin 
 glBegin(GL_POLYGON);        
		glVertex3d(-5,-5,0);        
		glVertex3d(5,-5,0);
		glVertex3d(5,5,0);
		glVertex3d(-5,5,0);
glEnd();

}
	glFlush();
	glutSwapBuffers();
}



 void mouseClick(int button, int state, int x, int y)
 {
    if 	((button == GLUT_LEFT_BUTTON) && (state == GLUT_DOWN))
	{

		mousedw(x, y, button);
	}
 }
 
 void mousedw(int x, int y, int but)
 {
 	printf("Mouse button %d pressed at %d %d\n", but, x, y);
 	gl_select(x,wHEIGHT-y); //Important: gl (0,0) ist bottom left but window coords (0,0) are top left so we have to change this!
 }
 
 void gl_select(int x, int y)
 {
 	GLuint buff[64] = {0};
 	GLint hits, view[4];
 	int id;
 
 	/*
 		This choose the buffer where store the values for the selection data
 	*/
 	glSelectBuffer(64, buff);
 
 	/*
 		This retrieve info about the viewport
 	*/
 	glGetIntegerv(GL_VIEWPORT, view);
 
 	/*
 		Switching in selecton mode
 	*/
 	glRenderMode(GL_SELECT);
 
 	/*
 		Clearing the name's stack
 		This stack contains all the info about the objects
 	*/
 	glInitNames();
 
 	/*
 		Now fill the stack with one element (or glLoadName will generate an error)
 	*/
 	glPushName(0);
 
 	/*
 		Now modify the vieving volume, restricting selection area around the cursor
 	*/
 	glMatrixMode(GL_PROJECTION);
 	glPushMatrix();
 		glLoadIdentity();
 
 		/*
 			restrict the draw to an area around the cursor
 		*/
 		gluPickMatrix(x, y, 1.0, 1.0, view);
		gluPerspective( 45.0,4.0/3.0,-110.0,0.0 );		
 
 		/*
 			Draw the objects onto the screen
 		*/
 		glMatrixMode(GL_MODELVIEW);
 
 		/*
 			draw only the names in the stack, and fill the array
 		*/
 		glutSwapBuffers();
 		mydisplay();
 
 		/*
 			Do you remeber? We do pushMatrix in PROJECTION mode
 		*/
 		glMatrixMode(GL_PROJECTION);
 	glPopMatrix();
 
 	/*
 		get number of objects drawed in that area
 		and return to render mode
 	*/
 	hits = glRenderMode(GL_RENDER);
 
 	/*
 		Print a list of the objects
 	*/
 	list_hits(hits, buff);
 
 	/*
 		uncomment this to show the whole buffer
 	* /
 	gl_selall(hits, buff);
 	*/
 
 	glMatrixMode(GL_MODELVIEW);
 }

 void gl_selall(GLint hits, GLuint *buff)
 {
 	GLuint *p;
 	int i;
 
 	mydisplay();
 
 	p = buff;
 	for (i = 0; i < 6 * 4; i++)
 	{
 		printf("Slot %d: - Value: %d\n", i, p[i]);
 	}
 
 	printf("Buff size: %x\n", (GLbyte)buff[0]);
 }
 

 void list_hits(GLint hits, GLuint *names)
 {
 	int i;
 
 	/*
 		For each hit in the buffer are allocated 4 bytes:
 		1. Number of hits selected (always one,
 									beacuse when we draw each object
 									we use glLoadName, so we replace the
 									prevous name in the stack)
 		2. Min Z
 		3. Max Z
 		4. Name of the hit (glLoadName)
 	*/
 
 	printf("%d hits:\n", hits);
 
 	for (i = 0; i < hits; i++)
 		printf(	"Number: %d\n"
 				"Min Z: %d\n"
 				"Max Z: %d\n"
 				"Name on stack: %d\n",
 				(GLubyte)names[i * 4],
 				(GLubyte)names[i * 4 + 1],
 				(GLubyte)names[i * 4 + 2],
 				(GLubyte)names[i * 4 + 3]
 				);
 
 	printf("\n");
 }



//reshape function
void myReshape(int w, int h)
{
   glClearColor(0.0,0.0,0.0,1.0);
  glViewport(0,0,w,h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  //glOrtho(-5,WIDTH*8+1,-5,HEIGHT*8+1,-3,3);
 gluPerspective( 45.0,4.0/3.0,-110.0,0.0 );
gluLookAt((GLdouble)WIDTH*4,(GLdouble)HEIGHT*4,-110.0,(GLdouble)WIDTH*4,(GLdouble)HEIGHT*4,0.0,0.0,1.0,0.0); 

  glMatrixMode(GL_MODELVIEW);
}


//main function
int main(int argc, char** argv){
  //printf("HELLO \n");
  //  srand(time(NULL));
        glutInit(&argc, argv);
	gameGrid.width=WIDTH; 
	gameGrid.height=HEIGHT; 
	createGrid(&gameGrid);

	void(*foo)(int value);

	
	glutReshapeFunc(myReshape);	
	glutInitDisplayMode(GLUT_DOUBLE);
	glutInitWindowSize (wWIDTH, wHEIGHT);

	glutCreateWindow("simple");     

	glutMouseFunc(mouseClick);

	glutDisplayFunc(mydisplay);    
	myReshape(wWIDTH,wHEIGHT);

	glutMainLoop();
	
}



Share this post


Link to post
Share on other sites
yaazz    122
@deathstar

This seems like a pretty good way to do acheive picking, but wont that method also draw to the screen?
How do you stop it from doing this?

Share this post


Link to post
Share on other sites
deadstar    536
Quote:
Original post by yaazz
@deathstar

This seems like a pretty good way to do acheive picking, but wont that method also draw to the screen?
How do you stop it from doing this?


Simply render to the backbuffer WITHOUT performing a flip. glReadPixels() reads from the backbuffer by default.

Oh, and it's DEADstar :P

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By povilaslt2
      Hello. I'm Programmer who is in search of 2D game project who preferably uses OpenGL and C++. You can see my projects in GitHub. Project genre doesn't matter (except MMO's :D).
    • By ZeldaFan555
      Hello, My name is Matt. I am a programmer. I mostly use Java, but can use C++ and various other languages. I'm looking for someone to partner up with for random projects, preferably using OpenGL, though I'd be open to just about anything. If you're interested you can contact me on Skype or on here, thank you!
      Skype: Mangodoor408
    • By tyhender
      Hello, my name is Mark. I'm hobby programmer. 
      So recently,I thought that it's good idea to find people to create a full 3D engine. I'm looking for people experienced in scripting 3D shaders and implementing physics into engine(game)(we are going to use the React physics engine). 
      And,ye,no money =D I'm just looking for hobbyists that will be proud of their work. If engine(or game) will have financial succes,well,then maybe =D
      Sorry for late replies.
      I mostly give more information when people PM me,but this post is REALLY short,even for me =D
      So here's few more points:
      Engine will use openGL and SDL for graphics. It will use React3D physics library for physics simulation. Engine(most probably,atleast for the first part) won't have graphical fron-end,it will be a framework . I think final engine should be enough to set up an FPS in a couple of minutes. A bit about my self:
      I've been programming for 7 years total. I learned very slowly it as "secondary interesting thing" for like 3 years, but then began to script more seriously.  My primary language is C++,which we are going to use for the engine. Yes,I did 3D graphics with physics simulation before. No, my portfolio isn't very impressive. I'm working on that No,I wasn't employed officially. If anybody need to know more PM me. 
       
    • By Zaphyk
      I am developing my engine using the OpenGL 3.3 compatibility profile. It runs as expected on my NVIDIA card and on my Intel Card however when I tried it on an AMD setup it ran 3 times worse than on the other setups. Could this be a AMD driver thing or is this probably a problem with my OGL code? Could a different code standard create such bad performance?
    • By Kjell Andersson
      I'm trying to get some legacy OpenGL code to run with a shader pipeline,
      The legacy code uses glVertexPointer(), glColorPointer(), glNormalPointer() and glTexCoordPointer() to supply the vertex information.
      I know that it should be using setVertexAttribPointer() etc to clearly define the layout but that is not an option right now since the legacy code can't be modified to that extent.
      I've got a version 330 vertex shader to somewhat work:
      #version 330 uniform mat4 osg_ModelViewProjectionMatrix; uniform mat4 osg_ModelViewMatrix; layout(location = 0) in vec4 Vertex; layout(location = 2) in vec4 Normal; // Velocity layout(location = 3) in vec3 TexCoord; // TODO: is this the right layout location? out VertexData { vec4 color; vec3 velocity; float size; } VertexOut; void main(void) { vec4 p0 = Vertex; vec4 p1 = Vertex + vec4(Normal.x, Normal.y, Normal.z, 0.0f); vec3 velocity = (osg_ModelViewProjectionMatrix * p1 - osg_ModelViewProjectionMatrix * p0).xyz; VertexOut.velocity = velocity; VertexOut.size = TexCoord.y; gl_Position = osg_ModelViewMatrix * Vertex; } What works is the Vertex and Normal information that the legacy C++ OpenGL code seem to provide in layout location 0 and 2. This is fine.
      What I'm not getting to work is the TexCoord information that is supplied by a glTexCoordPointer() call in C++.
      Question:
      What layout location is the old standard pipeline using for glTexCoordPointer()? Or is this undefined?
       
      Side note: I'm trying to get an OpenSceneGraph 3.4.0 particle system to use custom vertex, geometry and fragment shaders for rendering the particles.
  • Popular Now