I am using SDL with OpenGL and so far I have been doing everything in 2d (using glOrtho ())
Now I want to try to draw things in 3D, but, of course, since now I have chosen a 3-dimensional dimension in the mixture, things get complicated.
What I want to do, take the coordinates of the cursor screen, translate them into (?) World coordinates (the coordinates that I can use in OpenGL, since I now have a perspective, etc.), and draw a square in this position (cursor the mouse is in the center of the quad)
I have read several gluUnProject () tutorials and I understand what I have to do, but as I study it myself, it is very easy to get confused and misunderstand what I am doing.
As such, I basically copied from the examples I found.
Below is my code (I took out error checking, etc., trying to shorten it a bit)
As you can see, I have the variables mouseX, mouseY and mouseZ, from which mouseX and mouseY get their values from the SDL.
I tried using glReadPixel () to get mouseZ, but I'm not sure if I am doing this correctly.
The problem is that when I click, the square is not drawn in the correct position (I think, partly because I don’t know how to get mouseZ correctly, so I just replaced it with gluUnProject () 1,0?)
(wx, wy, wz) glTranslatef(), , , mouseZ. , , .
wz -499, , , , , ( )
- , , - , .
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
SDL_Surface* screen = 0;
SDL_Event event;
bool isRunning = true;
int mouseX, mouseY, mouseZ = 0;
GLint viewport[4];
GLdouble mvmatrix[16], projmatrix[16];
GLint realY;
GLdouble wx, wy, wz;
int main(int argc, char **argv) {
SDL_Init(SDL_INIT_EVERYTHING);
screen = SDL_SetVideoMode(800, 600, 32, SDL_OPENGL);
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glViewport(0, 0, 800, 600);
glClearDepth(1.f);
glClearColor(0, 0, 0, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.f, 1.f, 1.f, 500.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
while(isRunning) {
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) {
isRunning = false;
}
if(event.type == SDL_MOUSEBUTTONDOWN) {
if(event.button.button == SDL_BUTTON_LEFT) {
SDL_GetMouseState(&mouseX, &mouseY);
glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);
glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);
realY = viewport[3] - (GLint) mouseY - 1;
glReadPixels(mouseX, realY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &mouseZ);
gluUnProject((GLdouble)mouseX, (GLdouble)realY, 1.0, mvmatrix, projmatrix, viewport, &wx, &wy, &wz);
}
}
}
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glTranslatef(wx, wy, wz);
glBegin(GL_QUADS);
glColor4f(1.f, 0.f, 0.f, 1.f);
glVertex3f(-20.f, -20.f, 0.f);
glColor4f(0.f, 1.f, 0.f, 1.f);
glVertex3f(-20.f, 20.f, 0.f);
glColor4f(0.f, 0.f, 1.f, 1.f);
glVertex3f(20.f, 20.f, 0.f);
glColor4f(1.f, 0.f, 1.f, 1.f);
glVertex3f(20.f, -20.f, 0.f);
glEnd();
glPopMatrix();
SDL_GL_SwapBuffers();
}
SDL_FreeSurface(screen);
return 0;
}