OpenGL,访问冲突

时间:2015-06-19 17:54:47

标签: c++ opengl access-violation

我正在Visual Studio 2010中创建一个OpenGL项目。我正在关注youtube的教程。我不知道错误在哪里,我有这个错误:

Unhandled exception at 0x00000000 in OpenGL First Game.exe: 0xC0000005: Access violation.

Main.cpp的

#include <GL/glew.h>
#include <iostream>
#include <GL/glut.h>
#include "Sprite.h"

Sprite _sprite;

void Init() {
    glClearColor(0.0f, 1.0f, 1.0f, 1.0f);
    _sprite.Init(-1.0f, -1.0f, 1.0f, 1.0f);
}

void Render() {
    glClearDepth(1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    _sprite.Render();

    glutSwapBuffers();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(520, 200);
    glutInitWindowSize(800, 600);
    glutInitDisplayMode(GLUT_DOUBLE);
    glutCreateWindow("OpenGL [ 1 ]");
    glutDisplayFunc(Render);
    Init();
    glutMainLoop();
}

Sprite.cpp

#include <GL/glew.h>
#include "Sprite.h"

Sprite::Sprite(void){
    _vboID = 0;
}


Sprite::~Sprite(void){
    if(_vboID != 0)
        glDeleteBuffers(1, &_vboID);
}

void Sprite::Init(float x, float y, float width, float height){
    _x = x;
    _y = y;
    _width = width;
    _height = height;

    if(_vboID == 0){
        glGenBuffers(1, &_vboID);
    }

    float VertexData[12];
    // Prvi trougao
    VertexData[0] = x + width;
    VertexData[1] = y + height;
    VertexData[2] = x;
    VertexData[3] = y + height;
    VertexData[4] = x;
    VertexData[5] = y;

    // Drugi trougao
    VertexData[6] = x;
    VertexData[7] = y;
    VertexData[8] = x + width;
    VertexData[9] = y;
    VertexData[10] = x + width;
    VertexData[11] = y + height;

    glBindBuffer(GL_ARRAY_BUFFER, _vboID);
    glBufferData(GL_ARRAY_BUFFER, sizeof(VertexData), VertexData, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void Sprite::Render(){
    glBindBuffer(GL_ARRAY_BUFFER, _vboID);

    glEnableVertexAttribArray(0);

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 6);

    glDisableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

Sprite.h

#pragma once
#include <GL/glut.h>

class Sprite{
    public:
        Sprite(void);
        ~Sprite(void);
        void Init(float x, float y, float width, float height);
        void Render();
    private:
        float _x;
        float _y;
        float _width;
        float _height;
        GLuint _vboID; // Gluint na garantira da ce int biti 32 bita
};

1 个答案:

答案 0 :(得分:0)

您没有初始化GLEW。如果没有这样做,GLEW提供的所有入口点(OpenGL-1.1以外的所有入口点)都会保持未初始化状态,并且调用它们会导致程序崩溃。

添加

if( GLEW_OK != glewInit() ) { return 1; }
while( GL_NO_ERROR != glGetError() ); /* glewInit may cause some OpenGL errors -- flush the error state */

glutCreateWindow之后。