开发者

Shader from a file, program stopped working

Following an OpenGL tutorial,

in a part, where it creates a vertex shader, it uses the following method,

const GLchar* VertexShader =
{
    "#version 330\n"\

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

I just replaces this code, with my code which brings the shader from a file,

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

and BANG!

the code doesn't work anymore. What could be the issue?

the v.vert file contains the following code:

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


You don't have to split the read file into lines, just pass the whole file as it is. Also those '\n' are in the C code, because you can't have ordinary newlines in a C string. You must escape them. But this is not neccesary reading from a file.

And then you have a problem here:

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

readShaderFile returns a std::string that goes out of scope and the compiler may deconstrung the string instance right there. You must store the returned string in it's own variable and keep that around as long as you want to use its c_str();

Since this is supposedly on the global scope change it like this:

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


Your function to load the shader should be something like this :

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

Also, what are you doing after this line :

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

?
The temporary string gets destroyed, and the VertexShader contains a dangling pointer. What you need to do is this :

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜