/
Program.cpp
116 lines (93 loc) · 2.26 KB
/
Program.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include "Program.hpp"
#include "Shader.hpp"
#include "Error.hpp"
Program::Program()
: program(0)
{
program = glCreateProgram();
}
Program::~Program()
{
glDeleteProgram(program);
}
void Program::attach(const Shader& shader)
{
glAttachShader(program, shader.shader);
}
void Program::link()
{
info("Linking GLSL program %d.", program);
glLinkProgram(program);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLint length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
char logInfo[length];
glGetProgramInfoLog(program, length, NULL, logInfo);
fatal("Error linking program:\n%s", logInfo);
}
GLint num_shaders;
glGetProgramiv(program, GL_ATTACHED_SHADERS, &num_shaders);
GLuint shaders[num_shaders];
glGetAttachedShaders(program, num_shaders, NULL, shaders);
for (GLint i = 0; i != num_shaders; i++) {
glDetachShader(program, shaders[i]);
}
}
void Program::bind() const
{
glUseProgram(program);
}
void Program::unbind() const
{
glUseProgram(0);
}
Attribute Program::getAttribute(const char* name)
{
GLint location = glGetAttribLocation(program, name);
if (location == -1) {
fatal("Vertex attribute '%s' not found.");
}
return location;
}
Uniform Program::getUniform(const char* name)
{
GLint location = glGetUniformLocation(program, name);
if (location == -1) {
fatal("Uniform variable '%s' not found.");
}
return location;
}
Attribute::Attribute(GLuint loc)
: location(loc)
{}
void Attribute::enable()
{
glEnableVertexAttribArray(location);
}
void Attribute::disable()
{
glDisableVertexAttribArray(location);
}
void Attribute::set(GLint size, GLenum type, GLboolean normalized,
GLsizei stride, GLsizei offset)
{
glVertexAttribPointer(location, size, type, normalized, stride,
reinterpret_cast<const GLvoid*>(offset));
}
Uniform::Uniform(GLuint loc)
: location(loc)
{}
void Uniform::set1f(GLfloat value)
{
glUniform1f(location, value);
}
void Uniform::set1i(GLint value)
{
glUniform1i(location, value);
}
void Uniform::set_matrix4f(const GLfloat* value)
{
glUniformMatrix4fv(location, 1, GL_FALSE, value);
}