2D HUD graphics over 3D objects in Modern OpenGL

First we need to initialize our VBO(s) (Vertex Buffer Objects) with desired data. I’ll skip the 3D objects’ initialization and rendering in this post.

// Initialize the VBO data
float vert[9], colr[9]; // array variables to hold vertex data

// These values are according to screen size of 1920p width and 1080p height
vert[0] = 960.0f; vert[1] = 540.0f; vert[2] = 1.0f; // TOP
vert[3] = 900.0f; vert[4] = 10.0f; vert[5] = 1.0f; // LEFT
vert[6] = 500.0f; vert[7] = 540.0f; vert[8] = 1.0f; // RIGHT

glGenBuffers(1, &vbo);

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(GLfloat), vert, GL_STATIC_DRAW);
glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(gvPositionHandle);

// unbind buffers
glBindBuffer(GL_ARRAY_BUFFER, 0);

colr[0] = 1.0f; colr[1] = 0.0f; colr[2] = 0.0f; // TOP
colr[3] = 0.0f; colr[4] = 1.0f; colr[5] = 0.0f; // LEFT
colr[6] = 0.0f; colr[7] = 0.0f; colr[8] = 1.0f; // RIGHT
// COLOR VBO
glGenBuffers(1, &cvbo);
glBindBuffer(GL_ARRAY_BUFFER, cvbo);
glBufferData(GL_ARRAY_BUFFER, 9 * sizeof(GLfloat), colr, GL_STATIC_DRAW);
glVertexAttribPointer(gvColorHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(gvColorHandle);
// unbind buffers
glBindBuffer(GL_ARRAY_BUFFER, 0);

Now in your drawing function

void drawOpenGLWorld() {
.
.
.
// Draw all your 3D objects
// Now draw your 2D HUD
// Create an orthograpic matrix for WIDTH and HEIGHT of your screen's drawing area
Ortho = glm::ortho(0.0f, (float)width, (float)height, 0.0f);

glDisable(GL_DEPTH_TEST); // Disable the Depth-testing

glm::mat4 _guiMVP;
_guiMVP = Ortho * glm::mat4(1.0f); // Identity Matrix

glUniformMatrix4fv(MatrixID, 1, GL_FALSE, glm::value_ptr(_guiMVP));

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(gvPositionHandle);

glBindBuffer(GL_ARRAY_BUFFER, cvbo);
glVertexAttribPointer(gvColorHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(gvColorHandle);

glDrawArrays(GL_TRIANGLES, 0, 3); // draw first object
// un-bind the VBO
glBindBuffer(GL_ARRAY_BUFFER, 0);

glEnable(GL_DEPTH_TEST); // Enable the Depth-testing
.
.
.
}

Here’s a screenshot of an OpenGL window with dimensions of 1920×1080 having a triangle placed over 3D objects :

2D graphics over 3D world in OpenGL

You can also add Textures and other cool effects to your 2D HUD. So what are you waiting for; Go ahead .. .experiment on your own !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s