GLUT bitmap fonts have unexpected position - c++

I am making a game in OpenGL using GLUT on UNIX. It is a 3D game where the player can move side to side (x-axis) jump (y-axis) and is constantly moving forward and has to avoid oncoming obstacles (for my implementation the player actual stands still while the world constantly moves at the player).
I am having trouble when trying to draw a HUD with bitmap text on it. I have tried creating an orthogonal view and then drawing the text but it always ends up at a random spot on the x-axis and constantly moves towards the player with the world on the z-axis. Once it gets past the player it disappears (which is what happens to all the world objects to cut processing). I want the text in one place and to stay there.
gameSpeed = Accumulator*6;
DrawRobot(); //player
ModelTrans.loadIdentity(); //ModelTrans has helper functions to manipulate
ModelTrans.pushMatrix(); //the current matrix stack
ModelTrans.translate(vec3(0, 0, -gameSpeed)); //move the whole world
...Then I do a bunch of drawing of the game objects...
And here I attempt to do some bitmap fonts. Disabling the depth test helps put the text in front of all the other objects but the other code to create the orthogonal view actually could be commented out and I would still have the same problem.
ModelTrans.popMatrix();
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
ModelTrans.pushMatrix();
glLoadIdentity();
gluOrtho2D(0, WindowWidth, 0, WindowHeight);
glScalef(1, -1, 1);
glTranslatef(0, -WindowHeight, 0);
glMatrixMode(GL_MODELVIEW);
std::string str = "sup";
renderBitmapString(0.5 + xText, 5.0, GLUT_BITMAP_HELVETICA_18, str);
//xText adjusts for the moving left and right of the player
glMatrixMode(GL_PROJECTION);
ModelTrans.popMatrix();
glMatrixMode(GL_MODELVIEW);
glUseProgram(0);
glutSwapBuffers();
glutPostRedisplay();
printOpenGLError();
Here is some other code that may be of use:
void renderBitmapString(float x, float y, void *font, std::string s)
{
glRasterPos2f(x, y);
for (string::iterator i = s.begin(); i != s.end(); ++i)
{
char c = *i;
glutBitmapCharacter(font, c);
}
}
void Timer(int param)
{
Accumulator += StepSize * 0.001f;
glutTimerFunc(StepSize, Timer, 1);
}
void Reshape(int width, int height)
{
WindowWidth = width;
WindowHeight = height;
glViewport(0, 0, width, height);
}

I am making a game in OpenGL using GLUT on UNIX
First of all, you're not doing it on Unix, but most likely using X11. Also I'm pretty sure your OS is a variant of Linux, which is not Unix (a …BSD would be a true Unix).
Anyway, in this code snippet you're adjusting the projection, but not the modelview matrix
glMatrixMode(GL_PROJECTION);
ModelTrans.pushMatrix();
glLoadIdentity();
gluOrtho2D(0, WindowWidth, 0, WindowHeight);
glScalef(1, -1, 1);
glTranslatef(0, -WindowHeight, 0);
glMatrixMode(GL_MODELVIEW);
std::string str = "sup";
renderBitmapString(0.5 + xText, 5.0, GLUT_BITMAP_HELVETICA_18, str);
//xText adjusts for the moving left and right of the player
glMatrixMode(GL_PROJECTION);
ModelTrans.popMatrix();
glMatrixMode(GL_MODELVIEW);
I'm not entirely sure what ModelTrans is, but it has pushMatrix and popMatrix and if I assume, that those are just glPushMatrix and glPopMatrix then your code mises a
glPushMatrix();
glLoadIdentity()
…
glPopMatrix();
block acting on the Modelview matrix. Modelview and Projection matrices have their own stacks in OpenGL and must be pushed/poped individually.

Related

Why I can not get zoom in and out effect immediately but have to resize window first

I am new to OpenGL. I encounter a problem. Why I can not get zoom in and out effect in OpenGL immediately but have to resize window first and then I can see the image plotted become smaller or larger.
I am so sorry that I do not which part of program should I provide to clarify this problem.
I think the problem may be caused by mouse function?
void glutMouseWheel(int wheel_number, int direction, int x, int y)
{
if (direction == 1)
zoomFactor = 0.5*zoomFactor;
else
zoomFactor = 2* zoomFactor;
glutPostRedisplay();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-0.001*zoomFactor, 0.001*zoomFactor, -0.001*zoomFactor, 0.001*zoomFactor, -100, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
As you see I define a double zoomFactor to adjust the orthogonal volume to zoom the image. It should be fine, but I do not know why I still encounter this problem.
Right now you can change zoomFactor all you want but it won't get applied to the OpenGL state (via the code in resize()) until you resize the window.
The glutPostRedisplay() at the end of glutMouseWheel() will not cause the glutReshapeFunc() callback to run. It only schedules a glutDisplayFunc() call.
Move everything except the glViewport() call from reshape() to your glutDisplayFunc() callback:
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
}
void display()
{
// clear framebuffer
...
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-0.001*zoomFactor, 0.001*zoomFactor, -0.001*zoomFactor, 0.001*zoomFactor, -100, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// draw stuff
...
glutSwapBuffers();
}

Opengl Selecting 3D Models drawn with different projection matrics

I need to draw a cube and project it with the default projection matrix. Also, I want to draw a hud controlling the orientation of the sphere. The hud is projected with another projection matrix.
render()
{
DrawGUI(); // project GUI with another projection matrix
glPushMatrix();
glutSolidCube(); // project the cube with the default projection matrix
glPopMatrix();
glutSwapBuffers();
}
reshape()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(...);
...
}
DrawGUI()
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(...); // project the GUI with this matrix
glMatrixMode(GL_MODELVEIW);
glPushMatrix();
glLoadIdentity();
glBegin();
//... drawing GUI
glEnd();
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
#define BUFFER_LENGTH 64
void processSelection(int xPos, int yPos)
{
static GLuint selectBuff[BUFFER_LENGTH];
GLint hits, viewport[4];
glSelectBuffer(BUFFER_LENGTH, selectBuff);
glGetIntegerv(GL_VIEWPORT, viewport);
// Switch to projection and save the matrix
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glRenderMode(GL_SELECT);
glLoadIdentity();
gluPickMatrix(xPos, viewport[3] - yPos, 2,2, viewport);
glOrtho (-100, 100, -100, 100, -100, 100); // this line of code is the most
glMatrixMode(GL_MODELVIEW);
render();
hits = glRenderMode(GL_RENDER);
//...process hits
// Restore the projection matrix
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
The render part works well. Both the GUI and the cube are drawn without problem. However, the selection does not work as intended.
My question is: Since I project 3D models with different projection matrix, how should I deal with selection? I try to implement the typical selection buffer approach, but every time I click in the window, the selection buffer always contains the GUI even if I do not click on the GUI. Also, if I click on the cube, the selection buffer ends up with both the cube and the GUI.
If you use the selection buffer approach, you render with mixed projections as you do when doing the usual render. The only difference, is, that you apply that pick matrix as well. Also don't try to be too clever with the matrix pushing / poping. It rarely makes sense to use that in the projection matrix stack (hence it requires to have only 2 push levels, instead of the 32 for the modelview). Also don't use the reshape function to define the projection matrix.
DrawCube()
{
glMatrixMode(GL_MODELVEIW);
glLoadIdentity();
glutSolidCube();
}
DrawGUI()
{
glMatrixMode(GL_MODELVEIW);
glLoadIdentity();
glBegin();
//... drawing GUI
glEnd();
}
void render()
{
// base the projection on whats already in the projection
// matrix stack. For normal render this is identity, for
// selection it is a pick matrix.
glMatrixMode(GL_PROJECTION);
glPushMatrix();
gluOrtho2D(...); // project the GUI with this matrix
DrawGUI();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
gluPerspective(...);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
void display()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
render();
glutSwapBuffers();
}
#define BUFFER_LENGTH 64
void select(int xPos, int yPos)
{
static GLuint selectBuff[BUFFER_LENGTH];
GLint hits, viewport[4];
glSelectBuffer(BUFFER_LENGTH, selectBuff);
glGetIntegerv(GL_VIEWPORT, viewport);
// Switch to projection and augment it with a picking matrix
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPickMatrix(xPos, viewport[3] - yPos, 2,2, viewport);
glRenderMode(GL_SELECT);
render();
hits = glRenderMode(GL_RENDER);
//...process hits
}
Note that OpenGL selection mode is usually not GPU accelerated and hence very slow. Also it's been deprecated and removed from modern OpenGL versions. It's highly recommended to use either index buffer selection (i.e. render each object with a dedicated index "color") or perform manual ray-intersection picking into the scene data.

Disappearing object when resizeing screen (OpenGl)

I'm trying to load 3D models from .obj format and it draws the object on the scren without any problem but when I resize the screen everything disappear. Here's the code:
Obj* object = new Obj();
GLuint texture[1];
void handleResize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0,(double)w / (double)h,1.0,200.0);
}
void initRendering() {
object->GetObj("cube.obj");
glShadeModel(GL_LINEAR);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glEnable(GL_DEPTH_TEST);
}
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 27:
{
exit(0);
break;
}
}
}
void drawScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glPushMatrix();
glRotatef(45.0,0.0,1.0,0.0);
object->DrawObj();
glPopMatrix();
glutSwapBuffers();
glFlush();
}
int _tmain(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(400, 400);
glutCreateWindow("3D");
initRendering();
glutReshapeFunc(handleResize);
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutMainLoop();
return 0;
}
And here's the code for Obj.DrawObj():
glBegin(GL_TRIANGLES);
for(int i = 0;i < faces.capacity()-1;i++)
{
glVertex3f(vertices[faces[i].vertex1].cordinate1,vertices[faces[i].vertex1].cordinate2,vertices[faces[i].vertex1].cordinate3);
glVertex3f(vertices[faces[i].vertex2].cordinate1,vertices[faces[i].vertex2].cordinate2,vertices[faces[i].vertex2].cordinate3);
glVertex3f(vertices[faces[i].vertex3].cordinate1,vertices[faces[i].vertex3].cordinate2,vertices[faces[i].vertex3].cordinate3);
}
glEnd;
In your drawing code you set the projection matrix, which is good. However you set it to identity. In the resize handler you're setting the projection matrix as well, but you shouldn't do it there; yes I know the tutorials have it all there, but this is very bad style. You should move all the code currently in the reshape handler into the drawing handler, replacing the current setting of the projection matrix.
I can see that you're still confused by reading your PasteBin. Let me try to explain:
The reason why you can see your object the first time you draw it is because you have not set a projection matrix. So your object is drawn directly in normalized device coordinates (-1 to 1 range).
When you resize, you're setting the projection matrix for the first time, and this changes what viewing region is drawn to your screen. Your object as it is initially drawn is outside of the viewing region defined by your projection matrix (it is on top of the camera and I guess in front of the near plane. You have to move the object back away from the camera so that it is inside the view frustum. This is what datenwolf was suggesting.
However at the same time you introduced other errors into your code, particularly that you stopped resetting the projection matrix in handleResize. You have to always clear the projection matrix before you call gluPerspective, or else you will get a bogus result.
If you take the exact code from your pastebin, and add a glLoadIdentity to handleResize, I think that should work then:
void handleResize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION); //<--- add
glLoadIdentity(); //<--- add
gluPerspective(45.0,(double)w / (double)h,1.0,200.0);
}
Also, you're still clearing the projection matrix during the drawScene function. When you clear the matrix, you're throwing away the perspective setting that you just set in handleResize, you don't want to do that.
So basically:
Set the Projection matrix in handleResize and on initialization
Don't touch the projection matrix in drawScene
Translate the object so that it fits into the viewing frustum.

OpenGL Camera position and skybox

Been integrating this camera tutorial http://www.swiftless.com/tutorials/opengl/camera2.html and having a bit of trouble centering the camera in the skybox.
Using this code below makes my camera inside the box:
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-1.0, 1.0, -1.0*(GLfloat)h/(GLfloat)w,
1.0*(GLfloat)h/(GLfloat)w, -10.0, 10.0);
else
glOrtho(-1.0*(GLfloat)w/(GLfloat)h,
1.0*(GLfloat)w/(GLfloat)h, -1.0, 1.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
To draw the skybox, I followed this tutorial: http://sidvind.com/wiki/Skybox_tutorial
I've been trying to translate objects closer to the camera, but didn't work as I expected. Now I'm not sure what I need to do.
Appreciate any help.
First: Don'y apply the projection in the reshape handler. Otherwise simple things appear impossible (like doing a skybox). Second: For a skybox to work you must use the very same projection like for the rendering of the rest of the scene. What you should change is the translation of the modelview to 0, yet keeping the camera orientation.
You can do this by setting the last column of the modelview matrix to (0,0,0,1).
So this makes your rendering code like this:
void render_skybox()
{
push_modelview();
set_modelview_column(3, 0, 0, 1);
draw_skybox();
pop_modelview();
}
void render()
{
set_viewport();
set_projection();
apply_camera_transform();
render_skybox();
render_scene();
}

Draw camera position in specific view port

Most of this code should be fairly self explanatory. I got an display function and my view port function. There are two modes which is 4 small view ports in the window or one large.
I got one camera which can be moved and if in 4 view port mode just 3 fixed angles. The thing is I want the free moving cameras position to be displayed in the 3 other view ports. I tried doing it by drawing spheres using opengl but the problem is that then the position gets draw in the free roaming camera too as it shows the same scene.
It doesn't have to be a sphere, just something simple that represents the cameras spacial position in these three other views.
Drawing the scene once with camera object showing for the three viewports, render to texture. Clear and draw scene without camera object render to texture and then stitch these together before actually drawing the scene seems like a lot o work for something that should be easy.
void display(int what)
{
if(what==5){
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
camControll();}
if(what==1){
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(75,15,-5,0,5,-5,0,1,0);}
if(what==2){
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0,110,0,0,0,0,1,0,0);}
if(what==3){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, float(320) / float(240), 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
camControll();}
if(what==4){
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(185,75,25,0,28,0,0,1,0);}
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
drawScene();
drawCamera();
glutSwapBuffers();
}
void viewport(){
glEnable(GL_SCISSOR_TEST);
if(!divided_view_port)
{
glViewport(0, 0, w, h);
glScissor(0,0,640,480);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, w / h, 0.1f, 100.0f);
display(5);
}
else
{
////////////////////// bottom left - working
glViewport(0, 0, w/2, h/2);
glScissor(0,0,w/2,h/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, w / h, 0.1f, 300.0f);
display(1);
//////////////////////
////////////////////// top right - working
glViewport(w/2, h/2, w/2, h/2);
glScissor(w/2,h/2,w/2,h/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, w / h, 0.1f, 300.0f);
display(2);
//////////////////////
////////////////////// bottom right -working
glViewport(w/2, 0, w/2, h/2);
glScissor(w/2,0,w/2,h/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, w / h, 0.1f, 300.0f);
display(3);
////////////////////////
////////////////////////// top left
glViewport(0, h/2, w/2, h/2);
glScissor(0,h/2,w/2,h/2);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, w / h, 0.1f, 300.0f);
display(4);
///////////////////////////
}
glDisable(GL_SCISSOR_TEST);
glMatrixMode(GL_MODELVIEW);
}
So what I basically need is to hide this object in specific viewport.
Why not make that single Sphere object (or the entity responsible for drawing the sphere) aware of the "current viewport" (which happens to be the what variable in your code) and let it be invisible if it's the given viewport?
This solution exactly corresponds to the logic involved here sounds both simple and correct.
A more general solution would be to give each "camera" a GUID and make it available for the entity responsible for drawing Cameras to check the GUID of the "camera" bound to the viewport which is being rendered at the moment. If they happen to be equal, ignore the camera object during this draw pass.
I think that should be easy if you would just draw point, because if you want to see point in viewport, its center have to be in viewport, otherwise nothing of it is displayed even if you set huge point size. Then you have 2 options to eliminate flickering effect (as when you put 2 squares in the very same possition they will flicker one over another). You can just move that point little behind camera, or use nonzero value for near clipping plane in glFrustrum/gluPerspective call.. and well if you update point position every time you move camera you have no chance of seeing that point in your moving camera and you can use single scene.
And second option, I don't know if you can update just single viewport, but maybe just setting scene, displaying it to moving camera, drawing camera position and displaying it for other 3 viewports should be easy also..
Why don't you draw the sphere behind the moving camera's near plane? That should ensure that the moving camera doesn't see the sphere at all, but its position is clearly marked for the others.