I'm trying to render an video from OpenCV using OpenGL with the following vertices and indices:
static const GLint ImageIndices[] {
0, 1, 2,
0, 2, 3
};
static const GLfloat ImageVertices[] = {
// positions // texCoords
-1.0f, 1.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f,
1.0f, -1.0f, 1.0f, 0.0f,
1.0f, 1.0f, 1.0f, 1.0f
};
and following vertex and fragment shader:
#version 330 core
layout(location = 0) in vec2 vert_pos;
layout(location = 1) in vec2 tex_pos;
uniform mat3 trans1;
uniform mat3 trans2;
out vec2 texPos;
void main()
{
vec3 pos = vec3(-vert_pos.y, vert_pos.x, 0.0f);
vec3 rst;
if(pos.y < 0.0f)
{
rst = pos;
texPos = tex_pos;
}
else if(pos.y > 0.0f)
{
rst = pos;
texPos = tex_pos;
}
gl_Position = vec4(rst.x, rst.y, 0.0f, 1.0f);
//texPos = tex_pos;
}
#version 330 core
in vec2 texPos;
out vec4 fragColor;
uniform sampler2D tex;
uniform float width;
uniform float height;
void main()
{
fragColor = texture(tex, texPos);
}
and everything works well:
However, since I want to rotate the image using different matrix on the top and the bottom part, I changed the vertex shader to debug the coordinates of the image where texPos
is vec2(1.0f, 1.0f)
when pos.y > 0.0f
:
#version 330 core
layout(location = 0) in vec2 vert_pos;
layout(location = 1) in vec2 tex_pos;
uniform mat3 trans1;
uniform mat3 trans2;
out vec2 texPos;
void main()
{
vec3 pos = vec3(-vert_pos.y, vert_pos.x, 0.0f);
vec3 rst;
if(pos.y < 0.0f)
{
rst = pos;
texPos = tex_pos;
}
else if(pos.y > 0.0f)
{
rst = pos;
texPos = vec2(1.0f, 1.0f);
}
gl_Position = vec4(rst.x, rst.y, 0.0f, 1.0f);
//texPos = tex_pos;
}
and the output of the video is strange:
Why the video turned out to be like this and how can I fix it?
The vertex shader is executed per vertex, not per fragment. It is executed 6 times for the 6 vertices of the 2 triangles. You have changed the texture coordinates of the 3 vertices where pos.y > 0.0f
Since pos = vec3(-vert_pos.y, vert_pos.x, 0.0)
) you have changed the texture coordinates of the vertices, where x > 0.0:
x y u v x y u v
-1 1 0 1 -> -1 1 0 1
-1 -1 0 0 -> -1 -1 0 0
1 -1 1 0 -> 1 -1 1 1
1 1 1 1 -> 1 1 1 1
Actually only the texture coordinate of the vertex attribute with index 2 has changed. Hence, just the 1st triangle is effected: