summaryrefslogtreecommitdiff
path: root/engine/shader.cpp
blob: 04aa0319b003f17acdaf0a9109acd493e26ea3e9 (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
#include <fstream>
#include "shader.h"

bool GLBaseShader::shader_source(const char *filename) {
	std::ifstream inf(filename, std::ios_base::in);
	if(!inf.is_open()) {
		std::cerr << "Failed to load shader " << filename << std::endl;
		return false;
	}
	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);
	print_check_ogl_error();
	delete[] buffer;
	glCompileShader(shader);
	print_check_ogl_error();
	int p;
	glGetShaderiv(shader, GL_COMPILE_STATUS, &p);
	if(p == 0) {
		std::cerr << "Failed to compile shader:" << std::endl;
		char log[0xffff];
		int size;
		glGetShaderInfoLog(shader, 0xffff, &size, (GLchar*)&log);
		std::cerr << log << std::endl;
	}
	return shader;
}

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

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

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

bool GLShaderProgram::attach(GLBaseShader& shader) {
	glAttachShader(program, shader.shader);
	return !print_check_ogl_error();
}

bool GLShaderProgram::detach(GLBaseShader& shader) {
	glDetachShader(program, shader.shader);
	return !print_check_ogl_error();
}

bool GLShaderProgram::link() {
	glLinkProgram(program);
	bool error = print_check_ogl_error();
	int p;
	glGetProgramiv(program, GL_LINK_STATUS, &p);
	if(p == 0) {
		std::cerr << "Failed to link program:" << std::endl;
		char log[0xffff];
		int size;
		glGetProgramInfoLog(program, 0xffff, &size, (GLchar*)&log);
		printf(log);
	}
	return !error && p;
}

bool GLShaderProgram::use() {
	if(!glIsProgram(program)) program = glCreateProgram();
	glUseProgram(program);
	return !print_check_ogl_error();
}

void GLShaderProgram::remove() {
	glDeleteProgram(program);
}

void print_ogl_error(GLenum error) {
	unsigned char *buf = (unsigned char*)gluErrorString(error);
	std::cerr << "OpenGL: " << buf << std::endl;
}

bool print_check_ogl_error() {
	GLenum error = glGetError();
	if(error != GL_NO_ERROR)
		print_ogl_error(error);
	return error != GL_NO_ERROR;
}