将均匀的4x4矩阵传递给顶点着色器程序

时间:2014-08-16 18:22:04

标签: opengl glsl vertex-shader

我正在尝试学习OpenGL并遵循这个:http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/

直到他们开始将矩阵传递到顶点着色器以将三角形转换为我正在跟随的绘图的位置。

这是着色器程序,它开始出错:

#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
uniform mat4 MVP;

void main(){
    vec4 v = vec4(vertexPosition_modelspace,1); // Transform an homogeneous 4D vector

    gl_Position = MVP * v;

    //mat4 M = mat4(
    // vec4(1.0, 0.0, 0.0, 0.0),
    // vec4(0.0, 1.0, 0.0, 0.0),
    // vec4(0.0, 0.0, 1.0, 0.0),
    // vec4(0.0, 0.0, 0.0, 1.0)
    //);
    //gl_Position = M * v;
}

如果我使用注释掉的代码而不是行gl_Position = MVP * v;,那么一切正常。屏幕上绘有一个三角形。我也可以更改为M矩阵来移动三角形并缩放它。

为了让事情尽可能简单,我只是将顶点着色器传递给MVP字段中的单位矩阵。代码如下所示:

mat4x4 MVP;
mat4x4_identity(MVP);

int i,j;
for(i=0; i<4; ++i) {
    for(j=0; j<4; ++j)
        printf("%f, ", MVP[i][j]);
    printf("\n");
}

GLuint MatrixID = glGetUniformLocation(programID, "MVP");

// Send our transformation to the currently bound shader,
// in the "MVP" uniform
// For each model you render, since the MVP will be different (at least the M part)
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

我使用的是linmath.h而不是glm(https://github.com/datenwolf/linmath.h)。循环打印:

1.000000, 0.000000, 0.000000, 0.000000, 
0.000000, 1.000000, 0.000000, 0.000000, 
0.000000, 0.000000, 1.000000, 0.000000, 
0.000000, 0.000000, 0.000000, 1.000000, 

并确认MVP确实是一个单位矩阵。但是当我运行程序时,屏幕上看不到三角形。只有背景(深蓝色btw)。

您可以在此处看到更多主要的C程序:https://gist.github.com/avwhite/68580376ddf9a7ec9cb7

如果需要,我还可以提供主程序,顶点和片段着色器的完整源代码。

我认为这与MVP矩阵如何传递到着色器程序有关,但我对OpenGL来说是全新的,所以我真的不知道发生了什么。

2 个答案:

答案 0 :(得分:17)

glUniform*()调用当前程序的设置值。您需要在glUseProgram()电话之前致电glUniform*() 。在这个例子中:

glUseProgram(programID);
glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

答案 1 :(得分:1)

考虑使用 value_ptr 而不是&amp; MVP [0] [0]

glUniformMatrix4fv(MatrixID, 1, GL_FALSE, glm::value_ptr(MVP));
  

genType :: value_type const * glm :: value_ptr (genType const&amp; vec)

     

将常量地址返回到输入参数

的数据