Question

Not using gluUnProject properly - can you see the fix?

Asked by: thready

Hi Experts,
I have my GLFW code working to send me mouse position events now - but my translation from screen coordinates to world coordinates is wrong.  Can you see where I'm going wrong?  I'm drawing 4 lines (a rectangle) and when I put my mouse over any corner of this rectangle, the values I'm getting back are topleft =[-50, -50, -90] , bottomleft=[-50, 0, -90], topright=[50, -50,-90], bottomright=[50,0,-90]

void CGLFWTestProjectDlg::MouseMoved(int x, int y)
{
	GLdouble dx, dy, dz;
 
	GLint viewport [4] ;
	glGetIntegerv( GL_VIEWPORT, viewport ) ;
	GLdouble modmatrix[16], projmatrix[16];
	glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
	glGetDoublev(GL_MODELVIEW_MATRIX, modmatrix);
	gluUnProject(x, y, 1, modmatrix, projmatrix, viewport, &dx, &dy, &dz);
	CString S;
	S.Format("%lf, %lf, %lf\r\n", dx,dy, dz);
	ATLTRACE(S);
}
 
// the world is setup like this:
	// Get current time
	t = glfwGetTime();
 
	// Get window size
	glfwGetWindowSize( &width, &height );
 
	// Make sure that height is non-zero to avoid division by zero
	height = height < 1 ? 1 : height;
 
	// Set viewport
	glViewport( 0, 0, width, height );
 
	// Clear color and depht buffers
	glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
 
	// Set up projection matrix
	glMatrixMode( GL_PROJECTION );    // Select projection matrix
	glLoadIdentity();                 // Start with an identity matrix
	gluPerspective(                   // Set perspective view
		65.0,                         // Field of view = 65 degrees
		(double)width/(double)height, // Window aspect (assumes square pixels)
		1.0,                          // Near Z clipping plane
		100.0                         // Far Z clippling plane
		);
 
	// Set up modelview matrix
	glMatrixMode( GL_MODELVIEW );     // Select modelview matrix
	glLoadIdentity();                 // Start with an identity matrix
	gluLookAt(                        // Set camera position and orientation
		0.0, 0.0, 10.0,               // Camera position (x,y,z)
		0.0, 0.0, 0.0,                // View point (x,y,z)
		0.0, 1.0, 0.0                 // Up-vector (x,y,z)
		);
 
	// Here is where actual OpenGL rendering calls would begin...
 
	// Let us draw a triangle, with color!
	//glRotatef( 360.0f * (float)t, 0.0f, 1.0f, 0.0f );
 
	drawOneLine(-5,0, 5, 0);
	drawOneLine(-5,0, -5, 5);
	drawOneLine(-5,5,5,5);
	drawOneLine(5,5, 5,0);

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-01-16 at 15:02:59ID24059707
Topics

3D Graphics Software

,

3D Game Programming

,

OpenGL Graphics & Game Programming

Participating Experts
1
Points
500
Comments
8

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Marquee and return coordinates of two corners.
    OK, I need code to accomplish these things using Microsoft Visual C++ 6.0. 1) Make a CView window with a container able to view .GIF, .JPG and .BMP files. 2) Draw a rectangular marquee with the mouse, on top of the image. 3) Return the coordinates of the corners of the recta...
  2. how to draw a rectangle over an image???
    Hi. I need that the users of my site be able to draw a rectangle over an image (a country map) with the mouse, and also get the x0,y0 and x1,y1 coordinates of the rectangle. thanks andres garcia
  3. Drawing a rectangle
    I am writeing a program to use as a form editer. I would like to be able to tell what area I have selected by drawing a rectangle from the point at which the mouse when down to the mouses current position. There is no need to save the rectangle. I needs to disappear after t...
  4. Drawing a Rectangle
    Hello Experts, I want to select a rectangle area in side a richtextbox. I thought about drawing a rectangle inside a richtextbox in runtime. Is there an easier way? If not how can I draw a rectangle in runtime? You can also advice on another object that will display a text...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: StormSeedPosted on 2009-01-20 at 03:00:57ID: 23418822

Hi,

The important thing to remember here is that a point on the screen represents a line in the 3-D world.

The third parameter of gluUnProject is the screen Z coordinate, which represents how deep into the screen you are clicking.  0 is on the near clipping plane and 1 is on the far clipping plane and any number in between is between them.

If you're trying to select an in-world object with the mouse, i would recommend using OpenGL's picking functionality instead.

If, however, you are trying to select a certain point in the world, you are on the right track.  You should use gluUnProject with windowZ equal to 0 and equal to 1 to get the two vertices of your trace line-segment and calculate the intersection between this and whatever plane the user should be selecting the point on.  (Like the ground, for instance.)

 

by: threadyPosted on 2009-01-20 at 14:40:31ID: 23425136

Hi StormSeed,

Thanks for the great answer, but I just need to ask for a tiny bit of clarification on 2 things:

1-  What is OpenGL's picking functionality?  (what function should I lookup to read up about picking)

2-  if all my points are on the XY plane, do I still need to use this idea of intersection between 0 and 1?  I don't really understand why I would ever do this - can you give me an example?  (is this for when you are working in 3D?  Because I'm only working in 2D - drawing a 2D graph)... Sorry I forgot to mention that.

Many thanks!  :-)
Mike

 

by: StormSeedPosted on 2009-01-21 at 22:28:25ID: 23437019

Hi,

Since you had a projection matrix with a perspective frustum, I thought you were working in 3D.

Since you are working on the XY plane, the intersection is so simple we can essentially leave it out.

I am not certain whether the screen Z is linear between the clipping planes, but you could try a value of 0.0909090909 and see if it works.

Otherwise, I expect if you use 0 for the screen Z parameter, all your results should be exactly 10 times too small, so you could just multiply them by 10.  Although, your 65 degree FoV might mess this up, but it should work if you set it to 90.

If you are up for bigger modifications however, you could get rid of the projection matrix, and use gluOrtho instead of gluLookAt in the ModelView matrix.  This should give you better control of the view, so that you can easily fit the graph to the canvas.

 

by: StormSeedPosted on 2009-01-22 at 01:40:28ID: 23437796

Also, using gluOrtho will mean that you don't have to worry about the screen Z coordinate, since all the trace lines will be orthogonal to the plane that you are rendering the graph on.

To answer your question about the picking functionality, I recommend looking at the following functions:

glRenderMode
glInitNames
glPushName
glPopName

 

by: threadyPosted on 2009-01-22 at 06:30:24ID: 23439548

StormSeed,

Some things you said you don't explain - like where did you get the value 0.0909090909?  And why will my results be exactly 10 times smaller?  (how did you figure that out)?  And why will a FoV of 90 be better than 65?

I am now using gluOrtho without gluLookAt...  :-)

Mike

 

by: threadyPosted on 2009-01-22 at 06:31:08ID: 31537680

Still looking forward to hearing your other comments - you're very helpful!  :-)

 

by: StormSeedPosted on 2009-01-22 at 06:42:30ID: 23439667

Well, the 0.0909090909 is based on the (not necessarily correct) assumption that the screen Z interpolates linearly from the near plane to the far plane.  Since your position is at 10, looking downward and your near plane is at a distance of 1 and the far plane is at a distance of 100, the XY plane is 0.09090909 of the way from the near plane to the far plane.

The 'exactly 10 times smaller' comes from the fact that your near clipping plane is 10 times closer than the XY plane and therefore appears 10 times larger.  I am not certain whether FoV would have any effect, since I have never used any GLU functions, but I do know I tend to think in terms of a 90 degree FoV, so that was a disclaimer.

Good luck with the picking functionality.  You will likely need to learn a bit more about the clipping planes and the effects that certain matrix multiplications have on it as well.

 

by: threadyPosted on 2009-01-22 at 06:58:33ID: 23439835

Ahhhhhh, thanks for the great lessons!  :-)  Much appreciated.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...