OpenGL Shader无法编译

时间:2016-04-01 15:25:22

标签: c++ opengl shader

我正在尝试进入OpenGL。不幸的是我的着色器总是无法编译。存储着色器的文本文件成功读入字符串并传递给glShaderSource - 函数。由于到目前为止所做的一切都有效,我认为我的错误在着色器文件本身(顶点着色器,片段着色器)中的某处。我试图输出错误代码,但我只得到奇怪的符号。

    void GLSLProgram::compileShaders(const std::string& vertexShaderFilePath, const std::string& fragmentShaderFilepath)
{
    _programID = glCreateProgram();
    _vertexShaderID = glCreateShader(GL_VERTEX_SHADER);
    _fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);

    if (_vertexShaderID == 0){
        fatalError("Vertex shader failed to be created !");
    }
    _fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER);
    if (_fragmentShaderID == 0){
        fatalError("Fragment shader failed to be created !");
    }

    compileShader(vertexShaderFilePath, _vertexShaderID);
    compileShader(fragmentShaderFilepath, _fragmentShaderID);

    return;
}

void GLSLProgram::compileShader(const std::string& filePath, GLuint& id)
{
    std::ifstream vertexFile(filePath); 

    if (vertexFile.fail()){
        fatalError("Failed to open " + filePath);
        perror(filePath.c_str());
    }

    std::string fileContents = "";
    std::string line;

    while (std::getline(vertexFile, line)){
        fileContents.append(line + '\n');
    }

    vertexFile.close();
    const GLchar* contentsPtr = fileContents.c_str();
    glShaderSource(id, 1, &contentsPtr, nullptr); 

    glCompileShader(id);

    GLint success = 0;
    glGetShaderiv(id, GL_COMPILE_STATUS, &success); //returns success of most recent compilation
    if (success == GL_FALSE)
    {
        GLint maxLength = 0;
        glGetShaderiv(id, GL_INFO_LOG_LENGTH, &maxLength);

        // The maxLength includes the NULL character
        std::vector<char> errorLog(maxLength);
        glGetShaderInfoLog(id, maxLength, &maxLength, &errorLog[0]);

        // Provide the infolog in whatever manor you deem best.
        // Exit with failure.
        glDeleteShader(id); // Don't leak the shader.

        std::printf("%s\n", errorLog);
        fatalError("shader " + filePath + "failed to compile");

    }
}

片段着色器:

#version 130

out vec3 color;

void main(){
    color = vec3(1.0, 0.0, 0.0);
}

顶点着色器:

#version 130

in vec2 vertexPosition;

void main() {
    gl_Position.xy = vertexPosition;
    gl_Positionsition.z = 0.0;
    gl_Position.w = 1.0;
}

1 个答案:

答案 0 :(得分:2)

你的printf坏了。 errorLog作为向量传递&lt; char&gt;在格式字符串中写入“%s”时,类型不是有效类型。

而不是:

std::printf("%s\n", errorLog);

...写:

std::printf("%s\n", &(errorLog[0]));