OpenGL C ++窗口闪烁没有错误

时间:2014-05-26 05:34:41

标签: c++ opengl

我设法创建了一个n OpenGL窗口。据我所知,它有效,但当我编译&运行它,窗口出现,然后几乎瞬间关闭。它不会返回任何错误,所以我确定它与我的代码有关。

主类:

    #include <iostream>
    #include <GL/glew.h>
    #include "Display.h"

    int main(){
        Display display1(800, 600, "Hello World!");
        display1.isClosed();
        while (!display1.isClosed()){ //while window is opened
            display1.Update();
        }
     return 0;
    }

Display.h:

#pragma once
#ifndef DISPLAY_H
#define DISPLAY_H
#include <SDL2\SDL.h>
#include <string>
#undef main
class Display{
public:
    Display(int width, int height, const std::string& title);   
    void Clear(float r, float g, float b, float a);
    void Update();
    bool isClosed();
    virtual ~Display();
private:
    Display(const Display& other){}
    void operator=(const Display& other){}
    SDL_Window* m_window;
    SDL_GLContext m_glContext;  
    bool m_isClosed;
};
#endif // DISPLAY_H

Display.cpp:

#include "Display.h"
#include <string> 
#include <iostream>
#include <GL/glew.h>
#include <SDL2\SDL.h>
Display::Display(int width, int height, const std::string& title)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    //set attributes for bytes/color
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32); //reserved memory byts for color
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); //reserves for windows
    //window
    m_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
    m_glContext = SDL_GL_CreateContext(m_window); //lets opengGL access window directly
    GLenum status = glewInit(); //retrieve all OpenGL  
    if (status != GLEW_OK){ //check if glew has retrieved everything
        std::cerr << "GLEW FAILED TO INITIALIZED" << std::endl; } //error
}
Display::~Display(){
    //stop everything
    SDL_GL_DeleteContext(m_glContext);
    SDL_DestroyWindow(m_window);
    SDL_Quit();
}
void Display::Clear(float r, float g, float b, float a){
    glClearColor(r, g, b, a);
    glClear(GL_COLOR_BUFFER_BIT);
}
bool Display::isClosed(){
    return m_isClosed;
}
void Display::Update(){
    SDL_GL_SwapWindow(m_window);
    SDL_Event e;
    while (SDL_PollEvent(&e)){ //get an event, and store it in address of 'e'
        if (e.type == SDL_QUIT){ //if quit
            m_isClosed = true;
        } 
    }
}

0 个答案:

没有答案