summaryrefslogtreecommitdiff
path: root/shader.cpp
blob: 06943f0099e072f6da6220478594ec3ad2c81c41 (plain)
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
#include <fstream>
#include <stdexcept>

#include <boost/format.hpp>

#include "shader.h"

inline void gl_check_error(const char *msg) {
	GLenum error = glGetError();
	if(error != GL_NO_ERROR) {
		throw(std::runtime_error((boost::format("%s:\n%s") % msg % gluErrorString(error)).str()));
	}
}

void GLBaseShader::shader_source(const char *filename) {
	std::ifstream inf(filename, std::ios_base::in);
	if(!inf.is_open()) {
		throw(std::runtime_error((boost::format("Failed to load shader from file %s") % filename).str()));
	}
	inf.seekg(0, std::ios_base::end);
	int length = inf.tellg();
	inf.seekg(0, std::ios_base::beg);
	char *buffer = new char[length];
	inf.read(buffer, length);
	inf.close();

	glShaderSource(shader, 1, (const GLchar**)&buffer, &length);
	gl_check_error("Failed to set shader source");
	delete[] buffer;
	glCompileShader(shader);
	int p;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &p);
	if(p == 0) {
		char log[0xffff];
		int size;
		glGetShaderInfoLog(shader, 0xffff, &size, (GLchar*)&log);
		throw(std::runtime_error((boost::format("Failed to compile shader:\n%s") % log).str()));
	}
}

void GLBaseShader::shader_source(std::string& filename) {
	shader_source(filename.c_str());
}

GLBaseShader::GLBaseShader(GLenum type) {
	shader = glCreateShader(type);
}

GLBaseShader::~GLBaseShader() {
	glDeleteShader(shader);
}

/**
 * GLShaderProgram
 */
GLShaderProgram::GLShaderProgram() {
	program = glCreateProgram();
}

GLShaderProgram::~GLShaderProgram() {
	glDeleteProgram(program);
}

void GLShaderProgram::attach(GLBaseShader& shader) {
	glAttachShader(program, shader.shader);

	gl_check_error("Failed to attach shader to program");
}

void GLShaderProgram::detach(GLBaseShader& shader) {
	glDetachShader(program, shader.shader);

	gl_check_error("Failed to detach shader from program");
}

void GLShaderProgram::link() {
	glLinkProgram(program);
	gl_check_error("linkage");

	int p;
	glGetProgramiv(program, GL_LINK_STATUS, &p);
	if(p == 0) {
		char log[0xffff];
		int size;
		glGetProgramInfoLog(program, 0xffff, &size, (GLchar*)&log);
		throw(std::runtime_error((boost::format("Failed to link program:\n%s") % log).str()));
	}
}

void GLShaderProgram::use() {
	glUseProgram(program);

	gl_check_error("Failed to use program");
}

GLuint GLShaderProgram::get_program() {
	return program;
}