Shader* load_shader(std::string vertexFile, std::string fragmentFile)
{
#pragma region ReadShaders
std::string vertexCode;
std::string fragmentCode;
std::ifstream vShaderFile;
std::ifstream fShaderFile;
vShaderFile.exceptions(std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::badbit);
try {
vShaderFile.open(vertexFile);
fShaderFile.open(fragmentFile);
std::stringstream vShaderStream, fShaderStream;
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
vShaderFile.close();
fShaderFile.close();
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (std::ifstream::failure & e) {
std::cerr << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
return nullptr;
}
const GLchar* vShaderCode = vertexCode.c_str();
const GLchar* fShaderCode = fragmentCode.c_str();
#pragma endregion
GLuint vertex, fragment;
GLint success;
GLchar infoLog[512];
#pragma region VertexShaderLoad
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, nullptr);
glCompileShader(vertex);
glGetShaderiv(vertex, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertex, sizeof(infoLog), nullptr, infoLog);
std::cerr << "VERTEX SHADER COMPILE ERROR: " << std::endl;
std::cerr << infoLog << std::endl;
return nullptr;
}
#pragma endregion
#pragma region FragmentShaderLoad
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, nullptr);
glCompileShader(fragment);
glGetShaderiv(fragment, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragment, sizeof(infoLog), nullptr, infoLog);
std::cerr << "FRAGMENT SHADER COMPILE ERROR: " << std::endl;
std::cerr << infoLog << std::endl;
return nullptr;
}
#pragma endregion
#pragma region ShaderProgram
GLuint id = glCreateProgram();
glAttachShader(id, vertex);
glAttachShader(id, fragment);
glLinkProgram(id);
glGetProgramiv(id, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(id, sizeof(infoLog), nullptr, infoLog);
std::cerr << "SHADER PROGRAM LINK ERROR: " << std::endl;
std::cerr << infoLog << std::endl;
glDeleteShader(vertex);
glDeleteShader(fragment);
glDeleteProgram(id);
return nullptr;
}
glDeleteShader(vertex);
glDeleteShader(fragment);
#pragma endregion
return new Shader(id);
}