load and compile shaders

This commit is contained in:
Josh Holtrop 2011-04-28 18:47:06 -04:00
parent ba2c1d9c60
commit 5a1fed9a41
3 changed files with 95 additions and 2 deletions

4
template/f_shader.glsl Normal file
View File

@ -0,0 +1,4 @@
void main(void)
{
}

View File

@ -1,14 +1,87 @@
#define GL_GLEXT_PROTOTYPES
#include <sys/stat.h>
#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
using namespace std;
#define WIDTH 800
#define HEIGHT 600
GLuint vs, fs;
void init(int width, int height)
char * loadFile(const char *fname)
{
struct stat st;
if (stat(fname, &st) != 0)
return NULL;
if (st.st_size <= 0)
return NULL;
char * buff = new char[st.st_size + 1];
buff[st.st_size] = '\0';
return buff;
}
char *getShaderLog(GLuint id)
{
GLint log_length;
glGetShaderiv(id, GL_INFO_LOG_LENGTH, &log_length);
if (log_length > 0)
{
char *log = new char[log_length];
glGetShaderInfoLog(id, log_length, &log_length, log);
return log;
}
return NULL;
}
GLuint makeShader(GLenum shaderType, const char *fname)
{
GLuint id;
const char *source;
GLint status;
id = glCreateShader(shaderType);
if (id <= 0)
{
cerr << "Error creating shader object" << endl;
goto out;
}
source = loadFile(fname);
if (source == NULL)
{
fprintf(stderr, "Error reading file '%s'\n", fname);
goto cleanup_shader;
}
glShaderSource(id, 1, &source, NULL);
delete[] source;
glCompileShader(id);
glGetShaderiv(id, GL_COMPILE_STATUS, &status);
if (status != GL_TRUE)
{
cerr << "Error compiling shader" << endl;
char *log = getShaderLog(id);
cerr << "Shader Log:" << endl << log << endl;
delete[] log;
goto cleanup_shader;
}
return id;
cleanup_shader:
glDeleteShader(id);
out:
return 0;
}
bool init(int width, int height)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
@ -19,6 +92,16 @@ void init(int width, int height)
-1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
vs = makeShader(GL_VERTEX_SHADER, "v_shader.glsl");
fs = makeShader(GL_FRAGMENT_SHADER, "f_shader.glsl");
if (vs <= 0 || fs <= 0)
{
return false;
}
return true;
}
void display(void)
@ -47,7 +130,9 @@ int main(int argc, char *argv[])
}
SDL_WM_SetCaption(argv[0], argv[0]);
init(WIDTH, HEIGHT);
if (!init(WIDTH, HEIGHT))
return 2;
display();
SDL_Event event;
while (SDL_WaitEvent(&event))

4
template/v_shader.glsl Normal file
View File

@ -0,0 +1,4 @@
void main(void)
{
}