着色器来自文件,程序停止工作

Shader from a file, program stopped working

本文关键字:程序 停止工作 文件      更新时间:2023-10-16

遵循OpenGL教程,

在创建顶点着色器的零件中,它使用以下方法

const GLchar* VertexShader =
{
    "#version 330n"
    "layout(location=0) in vec4 in_Position;n"
    "layout(location=1) in vec4 in_Color;n"
    "out vec4 ex_Color;n"
    "void main(void)n"
    "{n"
    "       gl_Position = in_Position;n"
    "       ex_Color = in_Color;n"
    "}n"
};

我只是用我的代码替换了这个代码,它从文件中获得了着色器

string readShaderFile(string FileName)
{
string ShaderString = "";
ifstream shaderFile;
shaderFile.open(FileName);
    while(!shaderFile.eof())
    {
        string tempholder;
        getline(shaderFile, tempholder);      
        ShaderString.append(tempholder);
        ShaderString.append("n");
    }
shaderFile.close();
return ShaderString;
}
const GLchar *VertexShader = readShaderFile("v.vert").c_str();

砰!

代码不再工作。可能是什么问题?

v.vert文件包含以下代码:

#version 330
layout(location=0) in vec4 in_Position;
layout(location=1) in vec4 in_Color;
out vec4 ex_Color;
void main(void)
{
    gl_Position = in_Position;
    ex_Color = in_Color;
}

您不必将读取的文件拆分成行,只需按原样传递整个文件即可。此外,这些'\n'也在C代码中,因为在C字符串中不能有普通的换行符。你必须逃离他们。但这并不是从文件中读取所必需的。

然后你就遇到了一个问题:

const GLchar *VertexShader = readShaderFile("v.vert").c_str();

readShaderFile返回一个超出范围的std::字符串,编译器可能会在那里解除字符串实例的串。您必须将返回的字符串存储在它自己的变量中,并且只要您想使用它的c_str(),就必须保留它;

由于这是关于全球范围的变化,它是这样的:

static std::string strVertexShader = readShaderFile("v.vert");
GLchar const *VertexShader = strVertexShader.c_str();

加载着色器的函数应该是这样的:

string readShaderFile(const string fileName)
{
  std::ifstream shaderFile( fileName.c_str() );
  // find the file size
  shaderFile.seekg(0,std::ios::end);
  std::streampos          length = shaderFile.tellg();
  shaderFile.seekg(0,std::ios::beg);
  // read whole file into a vector:
  std::vector<char>       buffer(length);
  shaderFile.read(&buffer[0],length);
  // return the shader string
  return std::string( buffer.begin(), buffer.end() );
}

此外,你在这条线之后做什么:

const GLchar *VertexShader = readShaderFile("v.vert").c_str();


临时字符串将被销毁,并且VertexShader包含一个悬空指针。你需要做的是:

const std::string shaderProgram = readShaderFile("v.vert");
const GLchar *VertexShader = shaderProgram.c_str();
// create shader program
// etc