如何正确地将OpenGL代码添加到外部函数

How to properly add OpenGL code into an external function

本文关键字:添加 外部 函数 代码 OpenGL 正确地      更新时间:2023-10-16

我试图能够采取一些OpenGL代码,从顶点数组绘制对象,并将其添加到类文件。然而,只有当我在main.cpp文件中拥有它时,代码才会运行。在进入draw循环之前,我从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);
}

我的draw循环中的相关代码:

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);
}

然后,在我的draw函数中,我调用这个:

glUseProgram(noTextureShaderID);
glBindVertexArray(square.vao);
///many different uniforms added here
glDrawArrays(GL_TRIANGLES, 0, g_point_count);

但是,即使两个程序看起来有相同的代码,只有第一个版本生成一个立方体。在这方面我遗漏了什么?

你的代码在两种情况下都不相同,这与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,它完全在内部管理数组并允许您查询大小。