Search code examples
openglglslvertex-shader

OpenGL Vertex shader transformation and output


I have a simple vertex shader

#version 330 core

uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelMatrix;

in vec3 in_Position;

out vec3 pass_Color;

void main(void)
{             
    //gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(in_Position, 1.0);
    gl_Position = vec4(in_Position, 1.0);
    pass_Color = vec3(1,1,1);    
}

In my client code i have

    glm::vec4 vec1(-1,-1,0,1);//first
    glm::vec4 vec2(0,1,0,1);//second
    glm::vec4 vec3(1,-1,0,1);//third
    glm::mat4 m = projectionMatrix * viewMatrix * modelMatrix;  

    //translate on client side
    vec1 = m * vec1;
    vec2 = m * vec2;
    vec3 = m * vec3;

    //first vertex
    vertices[0] = vec1.x;
    vertices[1] = vec1.y;
    vertices[2] = vec1.z;
    //second
    vertices[3] = vec2.x;
    vertices[4] = vec2.y;
    vertices[5] = vec2.z;
    //third
    vertices[6] = vec3.x;
    vertices[7] = vec3.y;
    vertices[8] = vec3.z;

Now my question if i use no matrix multiplication in the shader and none in client code this will render me a nice triangle which strectch the whole screen, so i take it the vertex shader maps cordinates its given to the screen in a cordinate system with x=-1..1 and y=-1..1

If i do the matrix multiplication in the shader everything works nice. But if i comment out the code in the shader like shown and do it on the client i get odd results. Shouldnt it yield the same result?

Have i gotten it wrong thinking the output of the vertex shader gl_Position is 2D cordinates despite being a vec4?

Thanks for any help. I really like to understand what exactly the output of the vertex shader is in terms of vertex position.


Solution

  • The problem is in your shader as it accepts only 3 components of position. It is OK to set the forth coordinate to 1 (like you do it) if the coordinate is not in projection space yet.

    When you are doing the transformation in client space, the results are correct 4-component homogeneous vectors. You just need to use them as is in your vertex shader:

    in vec4 in_Position.
    ...
    gl_Position = in_Position.