我试图能够采用一些OpenGL代码从顶点数组中绘制对象并将其添加到类文件中。但是,代码仅在我的main.cpp文件中存在时才会运行。在进入绘制循环之前,我从main()函数调用init()。
init(){
GLuint containerVAO, VBO;
glGenVertexArrays(1, &containerVAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(containerVAO);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// Normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat),(GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
}
我的绘制循环中的相关代码:
glUseProgram(noTextureShaderID);
glBindVertexArray(containerVAO);
///many different uniforms added here
glDrawArrays(GL_TRIANGLES, 0, 36);
这会创建一个立方体没问题。 现在,当我替换init()函数中的代码时(初始化所有对象,而不仅仅是这个,我将其更改为:
init(){
square.init(noTextureShaderID, vertices[], NULL, 36);
//Square is a global variable within my main.cpp file
}
然后我使用这个功能:
void Mesh::init(const GLuint& shaderid, GLfloat vertices[], const char* tex_file, int num_vertices)
{
GLuint VBO;
vao = NULL; //This is a variable within the Mesh class
g_point_count = num_vertices;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(vao);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// Normal attribute
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
}
然后,在我的绘制函数中,我改为调用它:
glUseProgram(noTextureShaderID);
glBindVertexArray(square.vao);
///many different uniforms added here
glDrawArrays(GL_TRIANGLES, 0, g_point_count);
但即使两个程序似乎都有相同的代码,只有第一个版本生成一个多维数据集。我在这方面缺少什么?
答案 0 :(得分:4)
您的代码在两种情况下都不相同,这与OpenGL无关:
void Mesh::init(const GLuint& shaderid, GLfloat vertices[], const char* tex_file, int num_vertices)
{
// ...
glBufferData(..., sizeof(vertices), ...);
}
vertices
在这里通过引用传递,内部函数永远不会看到数组,sizeof(vertices)
将与sizeof(GLfloat*)
相同,在今天的机器上通常为4或8。因此,您的缓冲区只包含前一个或两个浮点数。
您必须明确地提供数组大小作为附加参数,或者使用一些(引用)更高级别的对象,如std:vector
,它在内部完全管理数组并允许您查询大小