-
Notifications
You must be signed in to change notification settings - Fork 0
/
shader.cpp
94 lines (86 loc) · 2.3 KB
/
shader.cpp
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
#include "shader.hpp"
// read text file into string
string readTextFile(const char * filename)
{
string line, returnstring;
// open file for reading
ifstream in;
in.open(filename);
if (in.is_open())
{
// read first line of file
getline(in, line);
while (in)
{
// read rest of the file line by line to returstring
returnstring += line + "\n";
getline(in, line);
}
return returnstring;
}
else
{
cerr << "Unable to open file " << filename << endl;
exit(-1);
}
}
// print out errors in shader program
void programErrors(const GLint program)
{
GLint length; // error log length
GLchar* log; // string for error log
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
log = new GLchar[length+1];
glGetProgramInfoLog(program, length, &length, log);
cout << "Compile error:\n" << log << endl;
delete [] log;
}
// print out errors in shader
void shaderErrors(const GLint shader)
{
GLint length; // error log length
GLchar* log; // error log
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
log = new GLchar[length+1];
glGetShaderInfoLog(shader, length, &length, log);
cout << "Compile error:\n" << log << endl;
delete [] log;
}
GLuint compileShader(GLenum type, const char * filename)
{
GLuint shader = glCreateShader(type);
// read shader source
string source = readTextFile(filename);
GLchar* cstr = new GLchar[source.size()+1];
const GLchar* p_cstr = cstr; // const pointer to cstr
strcpy(cstr, source.c_str());
// compile
glShaderSource(shader, 1, &p_cstr, NULL);
glCompileShader(shader);
// check for compile errors
GLint compiled;
glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled)
{
shaderErrors(shader);
}
return shader;
}
GLuint initProgram(GLuint vertexshader, GLuint fragmentshader)
{
GLuint program = glCreateProgram();
GLint linked;
glAttachShader(program, vertexshader);
glAttachShader(program, fragmentshader);
glLinkProgram(program);
glGetProgramiv(program, GL_LINK_STATUS, &linked);
if (linked)
{
glUseProgram(program);
}
else
{
programErrors(program);
}
return program;
}