现代Opengl:同时正交和透视投影

时间:2017-10-31 06:44:32

标签: c++ opengl perspectivecamera orthographic

我正在尝试使用现代opengl(https://preview.ibb.co/hif8t6/Screenshot_2017_10_31_09_59_27.png)显示两个立方体。第一个立方体通过正投影(左)显示,第二个立方体通过透视投影(右)显示。这工作正常,但我无法让左立方体落在正确的立方体后面。 这是相关的代码片段

    ourShader_ortho.Use();
    ourShader_persp.Use();

    glm::mat4 model_ortho, model1, model2, model;
    glm::mat4 view_ortho, view_persp;
    glm::mat4 orthographic;
    glm::mat4 perspective;

    model1 = glm::rotate(model, (GLfloat)glfwGetTime()*1.0f, glm::vec3(0.5f, 1.0f, 0.0f));
    model2 = glm::rotate(model, (GLfloat)glfwGetTime()*1.0f, glm::vec3(0.0f, 1.0f, 0.5f));
    model = model1 * model2;

    view_ortho = glm::translate(view_ortho, glm::vec3(200.0f, 200.0f, -150.0f));
    orthographic = glm::ortho(0.0f, (GLfloat)width, 0.0f, (GLfloat)height, 0.1f, 200.0f);

    view_persp = glm::translate(view_persp, glm::vec3(1.0f, 0.0f, -3.0f));
    perspective = glm::perspective(45.0f, (GLfloat)width/(GLfloat)height, 0.1f, 200.0f);

    GLint modelLoc_ortho = glGetUniformLocation(ourShader_ortho.Program, "model");
    GLint viewLoc_ortho = glGetUniformLocation(ourShader_ortho.Program, "view");
    GLint projLoc_ortho = glGetUniformLocation(ourShader_ortho.Program, "orthographic");

    glUniformMatrix4fv(modelLoc_ortho, 1, GL_FALSE, glm::value_ptr(model_ortho));
    glUniformMatrix4fv(viewLoc_ortho, 1, GL_FALSE, glm::value_ptr(view_ortho));
    glUniformMatrix4fv(projLoc_ortho, 1, GL_FALSE, glm::value_ptr(orthographic));   

    glBindVertexArray(VAO_O);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindVertexArray(0);

    GLint modelLoc_persp = glGetUniformLocation(ourShader_persp.Program, "model");
    GLint viewLoc_persp = glGetUniformLocation(ourShader_persp.Program, "view");
    GLint projLoc_persp = glGetUniformLocation(ourShader_persp.Program, "perspective");

    glUniformMatrix4fv(modelLoc_persp, 1, GL_FALSE, glm::value_ptr(model));
    glUniformMatrix4fv(viewLoc_persp, 1, GL_FALSE, glm::value_ptr(view_persp));
    glUniformMatrix4fv(projLoc_persp, 1, GL_FALSE, glm::value_ptr(perspective));    

    glBindVertexArray(VAO_P);
    glDrawArrays(GL_TRIANGLES, 0, 36);
    glBindVertexArray(0);

如何通过透视投影将具有正投影的立方体放在立方体后面?

1 个答案:

答案 0 :(得分:-2)

我不是OpenGL程序员,但这就是我的想法。

您使用glDrawArrays行绘制对象两次。对于投影矩阵,他们使用的是orthographicperspective矩阵。

然而,这些矩阵是使用不同的参数创建的:

view_ortho = glm::translate(view_ortho, glm::vec3(200.0f, 200.0f, -150.0f));
view_persp = glm::translate(view_persp, glm::vec3(1.0f, 0.0f, -3.0f));

我的猜测是你要统一翻译参数,以便多维数据集完全位于彼此的顶部。

E.g。

view_ortho = glm::translate(view_ortho, glm::vec3(200.0f, 200.0f, -150.0f));
view_persp = glm::translate(view_persp, glm::vec3(200.0f, 200.0f, -150.0f));