如何正确地将OpenGL代码添加到外部函数
How to properly add OpenGL code into an external function
我试图能够采取一些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
,它完全在内部管理数组并允许您查询大小。
相关文章:
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 当 lib 已添加到其他依赖项时,如何在 VS 中调试未解析的外部符号错误
- 如何将外部 dll 添加到我的 VS2019 项目?
- C#WPF和C++/CLI以及C++在C++/CLI中添加外部库错误
- 将外部 C++ 库添加到 CLion 项目
- cmake 添加外部已构建的库
- 通过cmake添加外部库(例如,特征)
- 如何使用Cygwin在c++中添加外部库
- 错误LNK2001:当从现有项目添加了一些文件时,无法解析外部符号
- 在日食中添加外部库时出错
- 为什么我不能添加到方法/函数外部的 ostringstream
- 如何使用 CMake 从根文件夹外部添加包含目录
- RootViewController 在其委托外部访问时不会添加子视图
- 向openFrameworks项目添加外部库
- 向activex dll (axvlc.dll)添加外部可访问的方法
- Rapidjson:在文档中添加外部子文档
- 我可以添加外部DLL到npapi插件,应该安装在浏览器中
- 如何为CMake添加外部DLL路径
- 如何在类C++中添加外部函数声明
- 在Qt中添加外部库时出错"File format not recognized"