YoggieEngine/MyGraphicsEngine/Shader.cpp

95 lines
2.2 KiB
C++

#include "MyGraphicsEngine/Shader.h"
Shader::Shader(const std::string vertexShaderPath, const std::string fragmentShaderPath)
{
char infoLog[512];
int succes;
char* vertexCode = readFile(vertexShaderPath.c_str());
unsigned int vertId = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertId, 1, &vertexCode, NULL);
glCompileShader(vertId);
glGetShaderiv(vertId, GL_COMPILE_STATUS, &succes);
if(!succes){
glGetShaderInfoLog(vertId, 512, NULL, infoLog);
spdlog::error( "Vertex shader has compile error {}", infoLog);
return;
}
char* fragmentCode = readFile(fragmentShaderPath.c_str());
unsigned int fragId = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragId, 1, &fragmentCode, NULL);
glCompileShader(fragId);
glGetShaderiv(fragId, GL_COMPILE_STATUS, &succes);
if(!succes){
glGetShaderInfoLog(fragId, 512, NULL, infoLog);
spdlog::error("Fragment shader has compile error {}", infoLog);
return;
}
id = glCreateProgram();
glAttachShader(id, vertId);
glAttachShader(id, fragId);
glLinkProgram(id);
int success;
glGetProgramiv(id, GL_LINK_STATUS, &success);
if(!success) {
glGetProgramInfoLog(id, 512, NULL, infoLog);
printf("ERROR::SHADER_PROGRAM::LINKING_FAILED\n %s", infoLog);
}
delete vertexCode;
delete fragmentCode;
}
char* Shader::readFile (const char* filePath){
spdlog::info("try Open file {}", filePath);
std::ifstream file ;
file.open(filePath);
if(file.is_open() == false){
spdlog::info("File not found.");
return nullptr;
}
// Determine the file size!
file.seekg(0, std::ios::end);
size_t filesize = file.tellg();
// Undo previous seek.
file.seekg(0, std::ios::beg);
spdlog::info("filesize: {}", filesize);
// Create a big enough buffer for the file
size_t bufferSize = filesize + 3;
char* FileBuffer = new char[bufferSize];
memset(FileBuffer, '\0', bufferSize);
// read the whole file
file.read(FileBuffer, filesize);
return FileBuffer;
}
void Shader::Use()
{
glUseProgram(id);
}