编译OpenGL着色器会导致语法错误

时间:2012-08-26 14:44:03

标签: c++ opengl shader

我有两个简单的着色器(顶点和片段)

顶点着色器

#version 330 core

//=============================================
//---[Structs/Vertex Data]---------------------
//=============================================

layout(location = 0) in vec3 vertexPosition_modelspace;

//=============================================
//---[Variables]-------------------------------
//=============================================

uniform mat4 projection;
uniform mat4 view;

//=============================================
//---[Vertex Shader]---------------------------
//=============================================

void main()
{
   gl_Position = projection * view * vertexPosition_modelspace;
}

片段着色器

#version 330 core

//=============================================
//---[Output Struct]---------------------------
//=============================================

out vec3 colour;

//=============================================
//---[Fragment Shader]-------------------------
//=============================================

void main()
{
    colour = vec3(1, 0, 0);
}

我正在尝试编译它们,我收到以下错误

错误C0000:语法错误,意外$ undefined,在令牌“未定义”时期待“::”

我认为这可能与我阅读文件的方式有关。以下是顶点着色器文件

的示例
std::string VertexShaderCode = FindFileOrThrow(vertex_file_path);
std::ifstream vShaderFile(VertexShaderCode.c_str());
std::stringstream vShaderData;
vShaderData << vShaderFile.rdbuf();
vShaderFile.close();

然后使用

编译该文件
char const *VertexSourcePointer = VertexShaderCode.c_str();
glShaderSource(VertexShaderID, 1, &VertexSourcePointer , NULL);
glCompileShader(VertexShaderID);

如何有效地读取文件并避免这些错误?

编辑:

正确编译:

const std::string &shaderText = vShaderData.str();
GLint textLength = (GLint)shaderText.size();
const GLchar *pText = static_cast<const GLchar *>(shaderText.c_str());
glShaderSource(VertexShaderID, 1, &pText, &textLength);
glCompileShader(VertexShaderID);

1 个答案:

答案 0 :(得分:6)

VertexShaderCode是您的文件名,而不是着色器字符串。那还在vShaderData。您需要将字符串从vShaderData复制出来,然后将其输入glShaderSource