2
\$\begingroup\$

To draw a 2D HUD (just a simple trianlge, for now) over 3D graphics in OpenGL I :

  • draw all 3D objects, then
  • call glDisable(GL_DEPTH_TEST) before drawing 2D HUD
  • draw 2D triangle
  • call glEnable(GL_DEPTH_TEST);

however it seems I am missing something and the triangle is only rendered when I set Model-View-Projection matrix to Identity :

DrawFrame() {
.
.. // Draw 3D objects
.
/*
*  Coordinates of 2D triangle
vert[0] = 0.0f; vert[1] = 0.5f; vert[2] = 0.0f;   // TOP
vert[3] = -0.5f; vert[4] = -0.5f; vert[5] = 0.0f;  // LEFT
vert[6] = 0.5f; vert[7] = -0.5f; vert[8] = 0.0f;   // RIGHT
*/

glDisable(GL_DEPTH_TEST);

glm::mat4 guiMVP = glm::mat4(1.0f);
//glm::mat4 guiMVP = Ortho * View * glm::mat4(1.0f);   // This does not render triangle
//glm::mat4 guiMVP = Projection * View * glm::mat4(1.0f);   // This DOES render triangle at its place but in 3D world
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &guiMVP[0][0]);
...
.. // render2D triangle
glEnable(GL_DEPTH_TEST);
}

OnSurfaceChanged(int width, int height) {

    glViewport(0, 0, width, height);

    aspect = (float) width / height;

    // Projection Matrix
    Projection = glm::perspective(45.0f, aspect, 0.1f, 10000.0f);
    // Orthographic Matrix for 2D HUD
    Ortho = glm::ortho(0.0f, (float)width, (float)height, 0.0f);
}

setCamera(float cameraX, float cameraY, float cameraZ, float cameraLX, float cameraLY, float cameraLZ) {
    // Camera/View matrix
    View = glm::lookAt(
        glm::vec3(cameraX, cameraY, cameraZ),     // Camera position
        glm::vec3(cameraLX, cameraLY, cameraLZ),     // pointing at
        glm::vec3(0, 1, 0)      // Angle
     );
}

here's my Vertex shader :

attribute vec3 in_Position;

uniform mat4 MVP;


void main(void) {
    vec4 v = vec4(in_Position, 1.0);

    gl_Position = MVP * v;

}

This is screenshot of what I want : Desired Output I DO get this output by using an Identity MVP matrix for 2D graphics. I know this is an ugly hack that works for now.

How to do this properly using Orthographic matrix ?

\$\endgroup\$
2
\$\begingroup\$

When drawing 2D over 3D you don't need to apply view matrix. You only need to apply the orthographic projection.

Applying the view matrix dones't work because it changes the position and rotation of the objects relative to the camera you don't want that.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.