3D网格投影到2D平面

时间:2016-07-29 09:24:23

标签: c++ opengl

当我尝试绘制网格时,我得到了类似的东西:

that

但是当我旋转我的网格时,它看起来像这样:

this

应该是这样的:

This

这是我的代码:

// Generate MVP matrix.
glm::mat4 Projection = glm::perspective(glm::radians(45.0f),
                                      4.0f / 3.0f, 0.1f, 100.0f);
glm::mat4 View = glm::lookAt(glm::vec3(4,0,4),
                             glm::vec3(0,0,0),
                             glm::vec3(0,0,1));
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 mvp = Projection * View * Model;
GLint matrixId = glGetUniformLocation(shader.getProgramId(), "MVP");

// Generate VBO and VAO.
float triangleVertices[] = {
    -0.5f, -0.5f, 0.0f, 1.0f,
    0.5f, 0.5f, 0.0f, 1.0f,
    0.5f, -0.5f, 0.0f, 1.0f,
    1.0f, 1.0f, 0.0f, 1.0f,
    1.0f, -1.0f, 0.0f, 1.0f,
    1.0f, -1.0f, 1.0f, 1.0f,
};
uint un_vertecesNum = sizeof(triangleVertices);
GLuint vbo;
glGenBuffers(1, &triangleBufferObject);
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertecesNum, 
             triangleVertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

// Begin main loop.
// Event handling here (Look for code below)
glClearColor(0.0,0.0,0.0,0.0);
glClear(GL_COLOR_BUFFER_BIT);
shader.Use();
glUniformMatrix4fv(matrixId, 1, GL_FALSE, &mvp[0][0]);

// Mesh display stuff.
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glDrawArrays(GL_TRIANGLES, 0, un_vertecesNum);
glDisableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);

shader.UnUse();
SDL_GL_SwapWindow(win);
// End main loop.

此处的事件句柄以及我如何旋转网格:

SDL_Event event;
while ( SDL_PollEvent(&event) )
{
    switch(event.type)
    {
    case SDL_KEYDOWN:
        switch(event.key.keysym.sym)
        {
            case SDLK_a:
                Model = glm::rotate(Model, 0.1f, 
                        glm::vec3(0.0f, 1.0f, 0.0f));
            case SDLK_d:
                Model = glm::rotate(Model, 0.1f,
                        glm::vec3(0.0f, -1.0f, 0.0f));
                break;
        }
        break;
     }
}
mvp = Projection * View * Model;

垂直着色器:

#version 130
uniform mat4 MVP;
attribute vec4 coord4d;
void main(void)
{
    vec4 temp = vec4(coord4d);
    gl_Position = temp*(MVP);
}

Frag shader:

#version 130
void main(void)
{
    gl_FragColor[0] = gl_FragCoord.x/640.0;
    gl_FragColor[1] = 0.2;
    gl_FragColor[2] = gl_FragCoord.y/480.0;
    gl_FragColor[3] = 1.0f;
}

如果你想知道Suzanne的样子:

img1 img1

我试着谷歌,在"典型错误"上阅读有关它的内容。页面或在stackoverflow上找到,但没有。

1 个答案:

答案 0 :(得分:2)

顶点着色器应该是MVP * temp,而不是相反。就像在现实世界中一样,在GLSL矩阵中,向量乘法是非交换的(这将是你正在寻找的“典型错误”)