循环内的glViewport导致较小的查看端口

时间:2018-11-29 12:03:32

标签: c++ opengl glfw

我有一个在macOS上运行的简单OpenGL程序:

glUseProgram(program);
glViewport(0, 0, mWidth, mHeight);
glClearColor(0.25f, 0.25f, 0.25f, 1.0f);

// Rendering Loop
while (glfwWindowShouldClose(mWindow) == false) {
    if (glfwGetKey(mWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
        glfwSetWindowShouldClose(mWindow, true);
    }

    // why can't view port here?
    glViewport(0, 0, mWidth, mHeight);

    // Background Fill Color
    glClear(GL_COLOR_BUFFER_BIT);

    glBindVertexArray(vao);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    // Flip Buffers and Draw
    glfwSwapBuffers(mWindow);
    glfwPollEvents();
}

如果我注释掉循环内的glViewport调用,则效果很好,三角形显示在窗口的中心,但是如果我取消注释,则三角形显示在窗口的左下角

下面是我的着色器和顶点数据代码:

const int mWidth = 1280;
const int mHeight = 800;
auto mWindow = glfwCreateWindow(mWidth, mHeight, "OpenGL", nullptr, nullptr);

const GLchar* vertex_shader_src =
    "#version 330 core\n"
    "layout (location = 0) in vec3 aPos;\n"
    "void main()\n"
    "{\n"
    "    gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
    "}";

const GLchar* fragment_shader_src =
    "#version 330 core\n"
    "out vec4 FragColor;\n"
    "void main()\n"
    "{\n"
    "    FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
    "}";

GLfloat vertices[] = {
    -0.5f, -0.5f, 0.0f,
    0.5f, -0.5f, 0.0f,
    0.0f,  0.5f, 0.0f
};

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float),
                      (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

@httpdigest commented一样,这是因为macOS的帧缓冲区大小是原来的2倍,如果我用glfwGetFramebufferSize进行查询并将其用作查看端口大小,它会很好地工作!