OpenGL VBO麻烦

时间:2014-03-13 18:29:46

标签: c++ arrays opengl stdvector vertex-buffer

好的,我正在尝试学习OpenGL。我成功地按照一个例子来渲染一个三角形。所以我试着继续前进,而不是使用示例中提供的顶点,而是尝试从文件中读取顶点(任意数量的顶点)。因为它是任意的,我读入std::vector然后尝试将其分配给数组以传递给glBufferData。 FWIW,我想绘制GL_LINE_STRIP,而不是GL_TRIANGLES。我的程序运行一秒钟,然后弹出一个窗口显示错误:

Debug assertion failed...然后它说...Expression: vector subscript out of range

我要发布的代码是呈现三角形的示例程序,但是,我已经注释了我从文件中读取的尝试(给出错误的代码)。所以你可以看到它出错的地方。我的版本中唯一真正改变的是更改数组中的硬编码顶点以便从输入中读取,然后在drawArray函数中我将GL_TRIANGLES更改为GL_LINE_STRIP。我知道我正在做一些非常愚蠢的事情而且我很想念它,我对OpenGL中的非即时模式感到困惑(我知道极端的菜鸟)。无论如何,这是代码:

void CreateVBO(void)
{
/*
string line;
int count = 0;
vector<GLfloat> vertices;
vector<GLfloat> colors;

ifstream myfile("C:\\Users\\Andrew\\Documents\\Visual Studio 2013\\Projects\\Control\\Control\\bin\\Debug\\GeoTemp.test");
if (myfile.is_open())
{
    while (getline(myfile, line))
    {
        float temp = (float)atof(line.c_str());

        if (count == 3)
        {
            vertices.push_back(1.0);
            colors.push_back(1.0);
            count = 0;
        }
        else
        {
            vertices.push_back(temp);
            colors.push_back(0.0);
            count++;
        }

        //cout << line << '\n';
    }
    myfile.close();
}

GLfloat* Vertices = &vertices[0];
GLfloat* Colors = &colors[0];
*/

GLfloat Vertices[] = {
    -0.8f, -0.8f, 0.0f, 1.0f,
    0.0f, 0.8f, 0.0f, 1.0f,
    0.8f, -0.8f, 0.0f, 1.0f
};

GLfloat Colors[] = {
    1.0f, 0.0f, 0.0f, 1.0f,
    0.0f, 1.0f, 0.0f, 1.0f,
    0.0f, 0.0f, 1.0f, 1.0f
};


GLenum ErrorCheckValue = glGetError();

glGenVertexArrays(1, &VaoId);
glBindVertexArray(VaoId);

glGenBuffers(1, &VboId);
glBindBuffer(GL_ARRAY_BUFFER, VboId);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
//glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(GLfloat), &vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);

glGenBuffers(1, &ColorBufferId);
glBindBuffer(GL_ARRAY_BUFFER, ColorBufferId);
glBufferData(GL_ARRAY_BUFFER, sizeof(Colors), Colors, GL_STATIC_DRAW);
//glBufferData(GL_ARRAY_BUFFER, colors.size()*sizeof(GLfloat), &colors[0], GL_STATIC_DRAW);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);

ErrorCheckValue = glGetError();
if (ErrorCheckValue != GL_NO_ERROR)
{
    fprintf(
        stderr,
        "ERROR: Could not create a VBO: %s \n",
        gluErrorString(ErrorCheckValue)
        );

    exit(-1);
}
}

1 个答案:

答案 0 :(得分:0)

我怀疑当您点击以下行时,vertices / colors个向量为空:

GLfloat* Vertices = &vertices[0];
GLfloat* Colors = &colors[0];

在文件阅读代码后添加尺寸检查:

if( vertices.empty() || colors.empty() )
{
    exit( -1 );
}