YoggieEngine/MyGraphicsEngine/Shader.cpp

94 lines
2.2 KiB
C++
Raw Normal View History

#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);
spdlog::info(vertexCode);
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;
}
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
//calculate buffer size to prevent memory issues
size_t ChunksInBuffer = filesize / Shader::CHUNK_SIZE;
size_t bufferSize = (ChunksInBuffer + 1) * Shader::CHUNK_SIZE;
char* FileBuffer = new char[bufferSize];
memset(FileBuffer, '\0', bufferSize);
size_t bytesRead= 0;
// read the whole file
while( file.eof() == false){
file.read(FileBuffer + bytesRead, CHUNK_SIZE );
bytesRead += CHUNK_SIZE;
}
FileBuffer[filesize + 1] = '\0';
return FileBuffer;
}
void Shader::Use()
{
// glUseProgam(id);
}