Sign in to follow this  

OpenGL How can I track the mouse cursor position and then draw a line ?

This topic is 2064 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

How can I track the mouse cursor position and then draw a line at that exact location?

I tried to do this myself by using glUnProject(); and store the 3 last values and use them as position for the glVertex3f(); vertex positioning obviously that didn't work it would draw the line but not at the exact location of the cursor or close enough that it wasn't noticeable after running the program.

So I was trying to deciper a way to do it and I'm 100% honestly stumped....


So in other words if someone knows how to do this feel free to tell me how you did it smile.png

OpenGL 3.0
WIN32 API
C++


Thanks in Advance

Share this post


Link to post
Share on other sites
Are you drawing a 2D line, or 3D line?

If it's 3D gluUnProject is defiantly what you need, mind posting your code?

If it's just 2D then you simply need to track your mouse(although it sounds like a 3D projection from your description.)

Also, could you possible provide a picture of a test scene so we can see exactly what your attempting to do?

Share this post


Link to post
Share on other sites
Hello yes I'm trying to draw a 3D Line here is the code thats most important in this case

The Setup :

[CODE]

void init ()
{
glClearColor(1.0,0.0,0.0,1.0);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90,SCREEN_HEIGHT/SCREEN_WIDTH,0.0,1500.0);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING); //we enable lighting, to make the 3D object to 3D
glEnable(GL_LIGHT0);
float col[]={1.0,1.0,1.0,1.0}; //light color is white
glLightfv(GL_LIGHT0,GL_DIFFUSE,col);

}

[/CODE]

Drawing The Line :

[CODE]
case WM_LBUTTONDOWN:

glBegin( GL_LINES );
glColor3f( 1.0f, 0.0f, 0.0f );
glVertex3f(posX, posY, 0.0f);
glVertex3f(posX, posY, posZ );
glEnd();

cout << "Test" << endl;


break;
[/CODE]

Displaying the graphics:

[CODE]
void display()
{

glLoadIdentity();
float pos[]={-1.0,1.0,-2.0,1.0}; //set the position
glLightfv(GL_LIGHT0,GL_POSITION,pos);
//glRotatef(angle,angle,0.0,2.0);
cout << name << endl;
// glCallList(cube);
for(std::vector<GLuint>::iterator I = cube.begin(); I != cube.end(); ++I) {
glCallList(*I);
}

glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_PROJECTION_MATRIX, projection);

GetCursorPos(&mouse);
ScreenToClient(hwnd, &mouse);

winX = (float)mouse.x;
winY = (float)mouse.y;
winY = (float)viewport[3] - winY;
glReadPixels(winX, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ );
cout << mouse.x << endl;
cout << mouse.y << endl;

SwapBuffers(hDC);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);


}
[/CODE]


And theres not much to see accept a black background with a red line that shows on the frustum only if I left click many times [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Hope that helps Edited by DarkHorseKnight

Share this post


Link to post
Share on other sites
A screenshot would still be useful.
"red line that shows on the frustum only if I left click many times"
This is not clear. Is something drawn? Is it drawn in the proper place?

The depth buffer is not infinitely precise. *Especially not at the far end of the frustum. You mustn't even use zero value of the near plane, because that screws the calculations. Look into the parameters of gluPerspective and what they mean.

So my guess: the lines are calculated fine except for the wrong perspective definition. Even if you define it correctly (with a >0.0 near plane value), the calculated world coordinates will be imprecise due to floating point errors. That means lines you want to draw at the end of the frustum may be culled (or partially culled) by the frustum, I hope it's clear.

[url="http://www.sjbaker.org/steve/omniv/love_your_z_buffer.html"]*Read this[/url]

Share this post


Link to post
Share on other sites
BTW, your whole logic is wrong, sorry I just noticed it now.

Sorry, it's hard to explain, there are fundamental flaws in your program.

OpenGL is not like DOS and EGA/VGA etc, where you can paint over-and over the scene and it will remain there like a canvas and everything will instantly get drawn on it. In OpenGL, commands are buffered, so you have to insert glFlush/glFinnish to force openGL to actually draw the stuff on the screen. Or you have to swap the buffers if you have double-buffer. Which you have (at least you use swappbuffers).

BUT:

You shouldn't (or better: mustn't) mix rendering with logic. You have rendering in your mouse handler logic, and you have logic stuff (reading and converting mouse coordinates) in your rendering. This thing can entirely screw rendering and logic, maybe it only works by accident in your case (we should see the WindProc to decide).

Frankly, the rendering and the logic is scattered all over the place, it's very hard to follow the program flow.



So:
Store the transformed (world) coordinates in a vector where you clicked with the mouse, then in the renderer, render the scene with the lines (you read the coordinates from the vector).
The most important thing is to decouple the logic from the render.


Maybe it's not clear at all, but honestly there are so many flaws in your program that it would be easier just to write the program for you than to explain it.


A note for rendering the lines: you should disable writing to the depth buffer ([i]glDepthMask[/i](false) ) so that you don't read the depth values of an already drawn line (unless you want that of course, but I doubt it).


Other problems: with lines, it's pretty much useless to use lighting. Lighting doesn't make things 3D as the comment in your code suggests. Maybe you copied it from a sloppy tutorial. Lighting makes the scene [i]look[/i] 3D, if there are polygons. Lighting requires normals. You don't specify any normals, and how would you do for lines anyway? This may cause that the lines you draw are black, since 0,0,0 is the default value of a normal (since the normals' coordinates are state variables, unlike vertex coordinates).



Maybe you are doing too much things at once. The thing you want to do is not the most beginner openGL topic IMHO, but you do seem like a total beginner (I'm sorry if I sound harsh). Edited by szecs

Share this post


Link to post
Share on other sites
Dude my code is messed up because I leave stuff that I can in my code so I can come back to it later and my program flow is fine I can render 3d models to the screen and rotate the camera around with np and see them. I even coloured the models with no tex cords for fun and got this really cool model texture effect. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

I was asking how to draw a line under the mouse cursor not a course of fixing my so called problems ??? that were needed enforcements for my ease of use. Some people prefer less stuff. I prefer more stuff [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] .

but good advice for someone who needs that :) Edited by DarkHorseKnight

Share this post


Link to post
Share on other sites
[quote name='DarkHorseKnight' timestamp='1337757835' post='4942460']
Dude my code is messed up because I leave stuff that I can in my code so I can come back to it later and my program flow is fine I can render 3d models to the screen and rotate the camera around with np and see them. I even coloured the models with no tex cords for fun and got this really cool model texture effect. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

I was asking how to draw a line under the mouse cursor not a course of fixing my so called problems ??? that were needed enforcements for my ease of use. Some people prefer less stuff. I prefer more stuff [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img] .

but good advice for someone who needs that [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
[/quote]

Well, I was trying to help since the [i]broken[/i] program flow may be the [i]cause[/i] of the problem.
But ignore me if you like, just like my first post that explicitly shows a bug that is related.

Share this post


Link to post
Share on other sites
gluUnproject gets you a point in 3D space, you are calling glBegin(LINES) with posX, posY, 0. What are those? Are they in 3D space or are they the mouse coordinates?

When you draw that line, you also do not show anything about the current matrix, is it going to be the identity? Are you able to rotate your camera? If so, you have to calculate the mouses start and end both in 3D space by calling gluUnproject 2 times, one with a depth from the depth buffer, and the other with a depth equal to your near plane.

Share this post


Link to post
Share on other sites

This topic is 2064 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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 xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glUseProgram(program.get());
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glUseProgram(0);
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
      glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
       
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
       
      #define NUM_LIGHTS 2
      struct Light
      {
          vec3 position;
          vec3 diffuse;
          float attenuation;
      };
      uniform Light Lights[NUM_LIGHTS];
       
       
    • By pr033r
      Hello,
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article (http://natureofcode.com/book/chapter-6-autonomous-agents/) inspirate from another code (here: https://github.com/jyanar/Boids/tree/master/src) but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch): https://github.com/pr033r/BachelorProject/tree/Optimalizing
      Exe file (if you want to look) and models folder (for those who will download the sources):
      http://leteckaposta.cz/367190436
      Thanks for any help...

    • By Andrija
      I am currently trying to implement shadow mapping into my project , but although i can render my depth map to the screen and it looks okay , when i sample it with shadowCoords there is no shadow.
      Here is my light space matrix calculation
      mat4x4 lightViewMatrix; vec3 sun_pos = {SUN_OFFSET * the_sun->direction[0], SUN_OFFSET * the_sun->direction[1], SUN_OFFSET * the_sun->direction[2]}; mat4x4_look_at(lightViewMatrix,sun_pos,player->pos,up); mat4x4_mul(lightSpaceMatrix,lightProjMatrix,lightViewMatrix); I will tweak the values for the size and frustum of the shadow map, but for now i just want to draw shadows around the player position
      the_sun->direction is a normalized vector so i multiply it by a constant to get the position.
      player->pos is the camera position in world space
      the light projection matrix is calculated like this:
      mat4x4_ortho(lightProjMatrix,-SHADOW_FAR,SHADOW_FAR,-SHADOW_FAR,SHADOW_FAR,NEAR,SHADOW_FAR); Shadow vertex shader:
      uniform mat4 light_space_matrix; void main() { gl_Position = light_space_matrix * transfMatrix * vec4(position, 1.0f); } Shadow fragment shader:
      out float fragDepth; void main() { fragDepth = gl_FragCoord.z; } I am using deferred rendering so i have all my world positions in the g_positions buffer
      My shadow calculation in the deferred fragment shader:
      float get_shadow_fac(vec4 light_space_pos) { vec3 shadow_coords = light_space_pos.xyz / light_space_pos.w; shadow_coords = shadow_coords * 0.5 + 0.5; float closest_depth = texture(shadow_map, shadow_coords.xy).r; float current_depth = shadow_coords.z; float shadow_fac = 1.0; if(closest_depth < current_depth) shadow_fac = 0.5; return shadow_fac; } I call the function like this:
      get_shadow_fac(light_space_matrix * vec4(position,1.0)); Where position is the value i got from sampling the g_position buffer
      Here is my depth texture (i know it will produce low quality shadows but i just want to get it working for now):
      sorry because of the compression , the black smudges are trees ... https://i.stack.imgur.com/T43aK.jpg
      EDIT: Depth texture attachment:
      glTexImage2D(GL_TEXTURE_2D, 0,GL_DEPTH_COMPONENT24,fbo->width,fbo->height,0,GL_DEPTH_COMPONENT,GL_FLOAT,NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, fbo->depthTexture, 0);
  • Popular Now