glGetxxx() problems with using gluUnProject()

I’m trying to get the object coordinates from the windows coordinates with the following code snippet.


void InsertSimulGLrender::OnMouseMove(UINT nFlags, CPoint point)
{
	GLdouble position[3] = {0};
	GLenum	error_code = 0;

	// Left mouse button
	if (nFlags & MK_LBUTTON)	{
		GLdouble modelMatrix[16] = {0};
		glGetDoublev(GL_MODELVIEW_MATRIX, &modelMatrix[0]);
		error_code = glGetError();
		GLdouble projMatrix[16] = {0};
		glGetDoublev(GL_PROJECTION_MATRIX, &projMatrix[0]);
		error_code = glGetError();
		if(gluUnProject(point.x, point.y, 0,
					modelMatrix, projMatrix, viewport,
					&position[0], &position[1], &position[2]) == GL_TRUE)
			printf("OpenGL coordinate clicked: %f %f %f
", position[0], position[1], position[2]);
		else
			error_code = glGetError();
	}
}

For some reason, the system is complaining about my use of glGetxxx() functions with the error code being “invalid operation.” I have checked the code relevant to setting the viewport, as well as the projection and modelview matrices.


void InsertSimulGLrender::OnSize(UINT nType, int cx, int cy)
{
	CWnd::OnSize(nType, cx, cy);
	if (0 >= cx || 0 >= cy || nType == SIZE_MINIMIZED) return;

	wglMakeCurrent(m_chdc->GetSafeHdc(), m_hglrc);	
	// Map the OpenGL coordinates.
	glViewport(0, 0, cx, cy);
	viewport[0] = 0;
	viewport[1] = 0;
	viewport[2] = cx;
	viewport[3] = cy;

	// Projection view
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	//glPopMatrix();
	glPushMatrix();				// push the matrix to be accessed

	// Set our current view perspective
	gluPerspective(35.0f, (float)cx / (float)cy, 0.01f, 2000.0f);
	// Model view
	glMatrixMode(GL_MODELVIEW);
	//glPopMatrix();
	glPushMatrix();				// push the matrix to be accessed
	wglMakeCurrent(NULL,NULL);	
}

I tried adding the glPushMatrix calls to ensure that the matrices are pushed onto the stack to be accessed by glGetxxx(), but no luck there. It would be great to hear some pointers about my mistakes on storing the matrices so that I can access the matrices properly. Thanks.

Can you clarify which glGet command is causing the error?

This may be silly question, but I have to ask… Do you have an active OpenGL context?

glGetDoublev function when getting modelview and projection matrices. Thanks for reminding me about the context. Forgot to call wglMakeCurrent() function to set the context.

Great. I hope it’s all working for you now.