GLSL着色器编译错误

时间:2015-05-26 22:11:21

标签: c++ opengl

我正在尝试使用Radeon HD 5470视频卡和fglrx AMD驱动程序在我的linux机器上编译简单的着色器。

我的顶点着色器代码

#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;

void main()
{

    gl_Position.xyz = vertexPosition_modelspace;
    gl_Position.w = 1.0;

}

从文件中读取代码

void Shader::load_from_file(const std::string& file)
{
    std::ifstream is(file, std::ios_base::in);
    if (is.is_open()) {
        std::string line{""};
        while(std::getline(is, line)) {
            // program_code_ is a std::string member
            program_code_ += "\n" + line; 
        }

        is.close();
    } else {
         throw Exception("Could not open shader source code file");
    }       
}

尝试编译

void Shader::build_shader()
{   
    const GLchar* tmp = program_code_.c_str();    
    const GLint tmplen = program_code_.length();

    std::cout << "Shader code: " << tmp << std::endl;

    glShaderSource(shader_handler_, 1, &tmp, &tmplen);
    CHECK_ERR();

    glCompileShader(shader_handler_);
    CHECK_ERR();
    //...
}

来自glGetShaderInfoLog的错误

Exception caught: Vertex shader failed to compile with the following errors:
ERROR: 0:1: error(#132) Syntax error: "<" parse error
ERROR: error(#273) 1 compilation errors.  No code generated

但在我调用glShaderSource之前,我打印到tmp指针的stdout值,它似乎是有效的着色器代码:

Shader code: 
#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;

void main()
{

    gl_Position.xyz = vertexPosition_modelspace;
    gl_Position.w = 1.0;

}

我的代码不会从内存中读取垃圾,但我无法理解错误。

另外

 % glxinfo | grep vertex_program
 % GL_ARB_vertex_program

1 个答案:

答案 0 :(得分:1)

逐行读取文件,并连接这些行似乎是个问题。

我不知道这是如何引入与您从着色器编译器获得的错误消息相匹配的错误,但正如评论中所建议的那样,立即读取整个文件可以解决问题。

以下行使用函数isrdbuf(您需要stringstream)从文件流#include <sstream>读取:

std::ostringstream contents;
contents << is.rdbuf();
program_code_ = contents.str();

有关此方法的详细信息以及与其他方法的比较,请参阅http://insanecoding.blogspot.de/2011/11/how-to-read-in-file-in-c.html