git.haldean.org ana / 430c158 lib / wbogl / shader_utils.cpp
430c158

Tree @430c158 (Download .tar.gz)

shader_utils.cpp @430c158raw · history · blame

/**
 * From the OpenGL Programming wikibook: http://en.wikibooks.org/wiki/OpenGL_Programming
 * This file is in the public domain.
 * Contributors: Sylvain Beucler
 */

#include <iostream>
using namespace std;

#include <SDL2/SDL.h>
#include <GL/glew.h>

/**
 * Display compilation errors from the OpenGL shader compiler
 */
void print_log(GLuint object) {
	GLint log_length = 0;
	if (glIsShader(object)) {
		glGetShaderiv(object, GL_INFO_LOG_LENGTH, &log_length);
	} else if (glIsProgram(object)) {
		glGetProgramiv(object, GL_INFO_LOG_LENGTH, &log_length);
	} else {
		SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_ERROR,
					   "printlog: Not a shader or a program");
		return;
	}

	char* log = (char*)malloc(log_length);
	
	if (glIsShader(object))
		glGetShaderInfoLog(object, log_length, NULL, log);
	else if (glIsProgram(object))
		glGetProgramInfoLog(object, log_length, NULL, log);
	
	SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_ERROR, "%s\n", log);
	free(log);
}

GLuint create_shader_from_string(const std::string &src, GLenum type) {
    GLuint res = glCreateShader(type);
    const GLchar *csrc = src.c_str();
    GLint len = src.length();
    glShaderSource(res, 1, &csrc, &len);
    glCompileShader(res);

	GLint compile_ok = GL_FALSE;
	glGetShaderiv(res, GL_COMPILE_STATUS, &compile_ok);
	if (compile_ok == GL_FALSE) {
		SDL_LogMessage(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_ERROR, "error loading shader:");
		print_log(res);
		glDeleteShader(res);
		return 0;
	}
    return res;
}