OpenGL渲染限制在屏幕的左下角

时间:2015-07-08 20:41:36

标签: c++ opengl glfw

所以我正在使用C ++开发一个OpenGL项目,我遇到了一个奇怪的问题,在创建了GLFWwindow并绘制到它之后,我所绘制的区域只包含了屏幕左下角四分之一。例如,如果屏幕尺寸为640x480,而我在(600,440)处绘制了40x40的正方形,则会显示在此处,而不是像我期望的那样显示在右上角:enter image description here

如果我将方块移动到不在640x480参数范围内的区域,它会被切断,如下所示:

enter image description here

我将从下面的main.cpp发布我的代码:

#define FRAME_CAP 5000.0;

#include <iostream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include "InputHandler.h"
#include "Game.h"
using namespace std;

void gameLoop(GLFWwindow *window){
    InputHandler input = InputHandler(window);

    Game game = Game(input);

    //double frameTime = 1.0 / FRAME_CAP;

    while(!glfwWindowShouldClose(window)){
        GLint windowWidth, windowHeight;
        glfwGetWindowSize(window, &windowWidth, &windowHeight);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0, windowWidth, 0.0, windowHeight, -1.0, 1.0);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glViewport(0, 0, windowWidth, windowHeight);

        game.render();
        game.handleInput();
        game.update();

        glfwSwapBuffers(window);
        glfwPollEvents();

    }

}

int main(int argc, const char * argv[]){
    GLFWwindow *window;

    if(!glfwInit()){
        return -1;
    }

    window = glfwCreateWindow(640.0, 480.0, "OpenGL Base Project", NULL, NULL);

    if(!window){
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glewInit();

    glfwMakeContextCurrent(window);

    gameLoop(window);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}

我不确定为什么会发生这种情况,但如果您有任何想法让我知道,谢谢!

1 个答案:

答案 0 :(得分:3)

对于那些喜欢我的人遇到这个问题,你需要将帧缓冲区大小传递给glViewport调用,如下所示:

GLFWwindow * window = Application::getInstance().currentWindow;
glfwGetFramebufferSize(window, &frameBufferWidth, &frameBufferHeight);
glViewport(0, 0, frameBufferWidth, frameBufferHeight);

在某些设备(主要是Apple Retina显示屏)中,像素尺寸不一定与视口尺寸1:1匹配。检查here以获取GLFW文档。

相关问题