openglglslopengl-3

OpenGL Geometry Shader rendering triangle instead of square from a point


I am trying to render a square from a single point, here is my geometry shader code:

#version 330 core
layout (points) in;
layout(triangle_strip, max_vertices=4) out;

void main(){
    vec4 pos=gl_in[0].gl_Position;
    gl_Position=pos+vec4(1,1,0,0);
    EmitVertex();
    gl_Position=pos+vec4(1,-1,0,0);
    EmitVertex();
    gl_Position=pos+vec4(-1,-1,0,0);
    EmitVertex();
    gl_Position=pos+vec4(-1,1,0,0);
    EmitVertex();
    EndPrimitive();
}

Vertex shader looks like this:

#version 330 core
layout (location=0) in vec3 position;

uniform mat4 view;
uniform mat4 projection;
uniform mat4 model;

void main(){
    gl_Position=projection*view*model*vec4(position,1.0);
}

It only renders a triangle, I'm not sure why it only renders a triangle.


Solution

  • The vertices define a triangle strip. Every group of 3 adjacent vertices forms a triangle and the winding order is defined by the winding of the first triangle (successive triangles have reversed order). When face culling is enabled, you need to care about the winding order. The default winding order of front faces is counter clockwise. Therefore you have to swap the 1st and 2nd vertex:

    void main(){
        vec4 pos=gl_in[0].gl_Position;
        gl_Position=pos+vec4( 1, -1, 0, 0);
        EmitVertex();
        gl_Position=pos+vec4( 1,  1, 0, 0);
        EmitVertex();
        gl_Position=pos+vec4(-1, -1, 0, 0);
        EmitVertex();
        gl_Position=pos+vec4(-1,  1, 0, 0);
        EmitVertex();
        EndPrimitive();
    }