gpt4 book ai didi

c++ - 使用面向对象的方法加载着色器

转载 作者:行者123 更新时间:2023-11-28 00:54:42 24 4
gpt4 key购买 nike

我的应用程序将成为一个使用 OpenGL 4.2GLFWGLEW 的 OpenGL 游戏。问题是关于从文件加载 GLSL 着色器。我使用一个名为 ShadersObject 的类来完成所有与着色器相关的任务。

class ShadersObject
{
public:
// ...
private:
// ...
void LoadFile(string Name, string Path);
string FolderPath;
Shaders ShaderList;
};

该类使用 ShaderObject 的映射来存储着色器。

enum ShaderType{ Vertex = GL_VERTEX_SHADER,
Geometry = GL_GEOMETRY_SHADER,
Fragment = GL_FRAGMENT_SHADER };

struct ShaderObject
{
const GLchar* File;
ShaderType Type;
GLuint Shader;
// ...
};

typedef map<string, ShaderObject> Shaders;

下面的方法我应该从一个文件加载GLSL着色器的源代码到ShaderList中的ShaderObject。因此它使用文件的 Path 和着色器的 Name 作为 ShaderList 映射中的字符串键命名。

void ShadersObject::LoadFile(string Name, string Path)
{
string FilePath = FolderPath + Path;
ifstream Stream(FilePath);

if(Stream.is_open())
{
cout << "Loading Shader from " << FilePath << endl;

string Output;
Stream.seekg(0, ios::end);
Output.reserve(Stream.tellg());
Stream.seekg(0, ios::beg);
Output.assign((istreambuf_iterator<char>(Stream)),istreambuf_iterator<char>());

// this line doesn't compile
strcpy(ShaderList[Name].File, Output.c_str());
}
else cout << "Can not load Shader from " << FilePath << endl;
}

我想使用 ShaderList[Name].File 中的值来使用 glShaderSourceglCompileShader 加载和编译着色器的另一种方法. glShaderSource 需要一个指向保存源代码的 const GLchar* 的指针。在我的例子中,这将是 &ShaderList[Name].File

前段时间我使用了 ShaderList[Name].File = Output.c_str(); 而不是现在无法编译的行。结果是 ShaderList 中只保存了指针,方法退出后源代码就没有了。这就是为什么我尝试使用 strcpy 但此函数不接受 const GLchar* 作为参数类型的原因。

如何将读取的文件保存到我的类(class)成员中?

最佳答案

这不是一个复杂的问题:存储字符串。将 Output 存储在您的 ShadersObject 类中。当你需要调用glShaderSource时,然后用string::c_str将它转换成一个const GLchar*

或者更好;不要存储它们中的任何一个; OpenGL 会在着色器对象中保留着色器字符串。您可以通过 API 从 OpenGL 查询着色器字符串。因此,在您的着色器对象中存储 OpenGL 已经存储的内容真的毫无意义。

关于c++ - 使用面向对象的方法加载着色器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12129926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com