带SDL2的现代OpenGL:如何绘制三角形

时间:2018-03-26 05:18:44

标签: c++ opengl sdl-2 opengl-3 opengl-4

我正在使用SDL2,我的目的是使用现代OpenGL绘制一个简单的三角形。使用现代OpenGL意味着不使用glBegin / glEnd等弃用函数。我的教程源是http://www.opengl-tutorial.org

我的代码:

int main(int ac, char** av) {
    SDL_Init(SDL_INIT_EVERYTHING);

    // Create SDL window with OpenGL support
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, 
    SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

    SDL_Window *pWindow = SDL_CreateWindow("SDL2 OpenGL", 
                                       SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                       600,
                                       400, SDL_WINDOW_OPENGL|SDL_WINDOW_RESIZABLE);

    // I do not know if required, but I create a GL context before calling 'gl3wInit'
    glcontext = SDL_GL_CreateContext(pWindow);
    gl3wInit();

    SDL_GL_SetSwapInterval(1);

    // I do not know if required, but I generate an initial array as done in many tutorials?
    GLuint vertexArrId;
    glGenVertexArrays(1,&vertexArrId);
    glBindVertexArray(vertexArrId);


    // My actual triangle consisting of 3 vertices
    GLfloat arrPos[] = {
        -1.0,-1.0,0.0,
        1.0,-1.0,0.0,
        0.0,1.0,0.0
    };

    // Generate buffer and store buffer id for my triangle data
    GLuint myBufferId;
    glGenBuffers(1, &myBufferId);
    glBindBuffer(GL_ARRAY_BUFFER, myBufferId);
    glBufferData(GL_ARRAY_BUFFER, sizeof(arrPos), arrPos, GL_STATIC_DRAW);

    // Tell open GL to use this buffer
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, myBufferId);
    glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, 0, (void*)0);

    bool green = false; // Toggle background clearing color between green and blue
    while(true)
    {
        green ? glClearColor(0.0,0.5,0.1,1.0) : glClearColor(0.0,0.,0.5,1.0);        
        green ^= true;            

        glClear(GL_COLOR_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3); // 3: Three vertices. Should draw the triangle?

        SDL_GL_SwapWindow(pWindow);
    }
    return 0;
}

我尽量保持代码尽可能短。

问题:三角形不可见。我的程序的输出是绿色或蓝色背景,因为每帧都切换背景颜色,所以我认为OpenGL至少起作用。

0 个答案:

没有答案