OpenGL 着色器程序的保存和加载(二进制)

背景

为了提高OpenGL 着色器程序的编译和链接速度,我们可以将程序保存为二进制进行加载,可以大幅度提升加载效率。

方法

以下是加载和保存二进制程序的方法。

// 加载着色器程序的二进制文件到已创建的着色器程序中
bool loadPragram(const std::string& programFilePath, unsigned int programId)
{
    // Load binary from file
    std::ifstream inputStream(programFilePath, std::ios::binary);
    if (!inputStream.is_open())
    {
        inputStream.close();
        WARN_LOG(" gl program binary file not exist! programfile:%s", programFilePath.c_str());
        return false;
    }
    unsigned int format = 0;
    inputStream.read(reinterpret_cast<char*>(&format), sizeof(GLenum));
    inputStream.seekg(sizeof(GLenum));
    std::istreambuf_iterator<char> startIt(inputStream), endIt;
    std::vector<char> buffer(startIt, endIt);  // Load file
    inputStream.close();
    // Install shader binary
    glProgramBinary(programId, format, buffer.data(), buffer.size());
    int success;
    glGetProgramiv(programId, GL_LINK_STATUS, &success);
 if (!success)
    {
        WARN_LOG("Install gl program failed.program file:%s,program id:%d ,format:%d", programFilePath.c_str(), programId, format);
        return false;
    }
       
    INFO_LOG("load gl program success.program name:%s", programFilePath.c_str());
    return true;
}
// 保存着色器的二进制信息到文件中
void saveProgram(const std::string& programFilePath,unsigned int programId)
{
    GLint length = 0;
    glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &length);

    // Retrieve the binary code
    std::vector<GLubyte> buffer(length + sizeof(GLenum));
    GLenum format = 0;
    glGetProgramBinary(programId, length, NULL, &format, buffer.data());

    // Write the binary to a file.
    std::ofstream out(programFilePath, std::ios::binary);
  out.write(reinterpret_cast<char*>(buffer.data()), length);
    out.close();
    INFO_LOG("save gl program success.program name:%s,binary format:%d", programFilePath.c_str(), format);
}

你可能感兴趣的:(opengl,着色器,着色器二进制程序)