I have an OpenGL
project which uses GLUT
(not freeglut) wherein I would like to display 2D text on the viewport at a fixed location. The rest of my objects are in 3D world co-ordinates.
This answer to a related old question says that,
the bitmap fonts which ship with GLUT are simple 2D fonts and are not suitable for display inside your 3D environment. However, they're perfect for text that needs to be overlayed on the display window.
I've tried the approach outlined in the accepted answer, but it does not give me the desired output. Following is a code snippet of the display function:
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0, 0.0, -(dis+ddis)); //Translate the camera
glRotated(elev+delev, 1.0, 0.0, 0.0); //Rotate the camera
glRotated(azim+dazim, 0.0, 1.0, 0.0); //Rotate the camera
.
.
.
draw 3D scene
.
.
.
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0, win_width, 0.0, win_height);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glRasterPos2i(10, 10);
string s = "Some text";
void * font = GLUT_BITMAP_9_BY_15;
for (string::iterator i = s.begin(); i != s.end(); ++i)
{
char c = *i;
glColor3d(1.0, 0.0, 0.0);
glutBitmapCharacter(font, c);
}
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glFlush();
glSwapBuffers();
}
A similar question to what I want seems to have been asked, but has no accepted answers by the author.
Answers in general seem to suggest using other libraries (mostly OS specific) to achieve the overlay. However, there is no clear indication to whether this can be achieved with GLUT
alone. Can it be done?
I ran into this same problem using glut to create a model of the solar system. Here's how I solved it: (using your code from above)
glDisable(GL_TEXTURE_2D); //added this
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0, win_width, 0.0, win_height);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
glRasterPos2i(10, 10);
string s = "Some text";
void * font = GLUT_BITMAP_9_BY_15;
for (string::iterator i = s.begin(); i != s.end(); ++i)
{
char c = *i;
glColor3d(1.0, 0.0, 0.0);
glutBitmapCharacter(font, c);
}
glMatrixMode(GL_PROJECTION); //swapped this with...
glPopMatrix();
glMatrixMode(GL_MODELVIEW); //...this
glPopMatrix();
//added this
glEnable(GL_TEXTURE_2D);
You'll note i switched glMatrixMode(GL_PROJECTION);
and glMatrixMode(GL_MODELVIEW);
near the end. I decided to do this because of this website. I also has to surround the code section with glDisable(GL_TEXTURE_2D)
and glEnable(GL_TEXTURE_2D)
.
Hope that helps- I worked for me. My solar system uses classes to perform all of this, I'd be happy to share more details upon request.