-
Notifications
You must be signed in to change notification settings - Fork 0
/
shader.cpp
95 lines (74 loc) · 2.22 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
95
#include "shader.hpp"
#include "gl_error.hpp"
#include <exception>
#include <stdexcept>
#include <iostream>
#include <fstream>
#include <vector>
#include "gl.hpp"
using namespace plush;
Shader::Shader(GLenum shaderType)
{
m_id = glCreateShader(shaderType);
GLError::check("Shader::Shader()");
}
Shader::Shader(GLenum shaderType, const std::string &filename) : Shader(shaderType)
{
load(filename);
}
Shader::~Shader()
{
glDeleteShader(m_id);
}
void Shader::loadFromString(const std::string &text)
{
const char *textPointers[1] = { text.c_str() };
const GLint lengths[1] = { static_cast<GLint>(text.length()) };
glShaderSource(m_id, 1, textPointers, lengths);
GLError::check("Shader::loadFromString(): after glShaderSource()");
glCompileShader(m_id);
GLError::check("Shader::loadFromString(): after glCompileShader()");
// even if compilation succeeds, the log can still contain warnings
// so show it every time it's not empty
GLchar log[1024];
glGetShaderInfoLog(m_id, 1024, NULL, log);
if (log[0] != '\0') {
std::cerr << log << "\n";
}
GLint success;
glGetShaderiv(m_id, GL_COMPILE_STATUS, &success);
if (!success) {
throw GLError("Shader::loadFromString(): compilation failed");
}
}
void Shader::load(const std::string &filename)
{
std::fstream in;
in.open(filename, std::ios_base::in | std::ios_base::binary);
if (!in.is_open())
throw GLError("Shader::load(): could not open file: " + filename);
std::vector<char> buf;
buf.reserve(1024);
for (;;) {
int c = in.get();
if (c < 0) break;
buf.push_back(static_cast<char>(c));
}
if (in.fail() && !in.eof())
throw GLError("Shader::load(): error reading file: " + filename);
// add terminating zero to make a valid C-style string
buf.push_back('\0');
loadFromString(buf.data());
}
FragmentShader::FragmentShader() : Shader(GL_FRAGMENT_SHADER)
{
}
FragmentShader::FragmentShader(const std::string &filename) : Shader(GL_FRAGMENT_SHADER, filename)
{
}
VertexShader::VertexShader(): Shader(GL_VERTEX_SHADER)
{
}
VertexShader::VertexShader(const std::string &filename) : Shader(GL_VERTEX_SHADER, filename)
{
}