-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShaderClass.cpp
More file actions
95 lines (79 loc) · 2.34 KB
/
ShaderClass.cpp
File metadata and controls
95 lines (79 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "ShaderClass.h"
std::string getFileContents(const char* filename)
{
std::ifstream in(filename, std::ios::binary);
if (in)
{
std::string content;
in.seekg(0, std::ios::end);
content.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&content[0], content.size());
in.close();
return content;
}
throw (errno);
}
Shader::Shader(const char* vertexFile, const char* fragmentFile)
{
std::string vertexCode = getFileContents(vertexFile);
std::string framentCode = getFileContents(fragmentFile);
const char* vertexSource = vertexCode.c_str();
const char* fragmentSource = framentCode.c_str();
//Creating vertex shader object
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
//Attaching the vertex shader source to the object
glShaderSource(vertexShader, 1, &vertexSource, NULL);
//Compiling the vertex shader source
glCompileShader(vertexShader);
CompileErrors(vertexShader, "VERTEX");
//Creating fragment shader object
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
//Attaching the fragment shader source to the object
glShaderSource(fragmentShader, 1, &fragmentSource, NULL);
//Compiling fragment shader source
glCompileShader(fragmentShader);
CompileErrors(fragmentShader, "FRAGMENT");
//Creating shader program
ID = glCreateProgram();
//Attaching vertex and fragment shaders to shader program
glAttachShader(ID, vertexShader);
glAttachShader(ID, fragmentShader);
//Linking all the shaders into the shader program
glLinkProgram(ID);
CompileErrors(ID, "PROGRAM");
//Deleting vertex and fragment shader objects, as they have been used already
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
void Shader::Activate()
{
glUseProgram(ID);
}
void Shader::Delete()
{
glDeleteProgram(ID);
}
void Shader::CompileErrors(unsigned int shader, const char* type)
{
GLint hasCompiled;
char infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &hasCompiled);
if (hasCompiled == GL_FALSE)
{
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "SHADER_COMPILATION_ERROR for: " << type << "\n" << std::endl;
}
}
else
{
glGetProgramiv(shader, GL_COMPILE_STATUS, &hasCompiled);
if (hasCompiled == GL_FALSE)
{
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
std::cout << "SHADER_LINKING_ERROR for: " << type << "\n" << std::endl;
}
}
}