Search code examples
openglcoordinate-systemsvertexcoordinate-transformationvertices

OpenGL z value. Why negative value in front?


Opengl has right-hand coordinate system. It means z values increase towards me.

right-hand coordinate system
right-hand coordinate system

I draw two triangles:

float vertices[] =
{
     //position                     //color
     //triangle 1
     0.0f,  1.0f, -1.0f,            1.0f, 0.0f, 0.0f,//0
    -1.0f, -1.0f, -1.0f,            1.0f, 0.0f, 0.0f,//1
     1.0f, -1.0f, -1.0f,            1.0f, 0.0f, 0.0f,//2
     //triangle 2
     0.0f, -1.0f, 0.0f,             0.0f, 0.0f, 1.0f,//3
     1.0f,  1.0f, 0.0f,             0.0f, 0.0f, 1.0f,//4
    -1.0f,  1.0f, 0.0f,             0.0f, 0.0f, 1.0f//5
};

Why triangle 1 is in front? Triangle 2 should be in front, because of 0.0f > -1.0f.

I have only gl_Position = vec4(aPos, 1.0); in vertex shader.

After it, if I translate vertices by z=-3 in vertex shader, this translation behaves as it should be. Object becomes further.


Solution

  • Why triangle 1 is in front? Triangle 2 should be in front, because of 0.0f > -1.0f.
    I have only gl_Position = vec4(aPos, 1.0); in vertex shader.

    Of course the red triangle is in front of the blue one, because you don't use any projection matrix. You forgot to transform the input vertex by the projection matrix before you assign the vertex coordinate to gl_Position.

    This causes that the vertices are equal to the normalized device space coordinates. In normalized device space the z-axis points into the viewport and the "projection" is orthographic and not perspective.

    You have to do something like this:

    in vec3 aPos;
    mat4 modelProjectionMatrix;
    
    void main()
    {
        gl_Position = modelProjectionMatrix * vec4(aPos, 1.0);
    }