Read me About Demoscene? Links Contact

Simple fragment shader class

So, experimenting with shaders et al made me generate the following C++ class for handling the fragment shaders. It can easily be extended to vertex shaders (and to shader programs covering both items).

It’s fairly easy to use:

 

FragmentShader fs1("shaders/test.fs", true); // load from file

FragmentShader fs2("void main(void){ gl_FragColor=vec4(0.0,1.0,0.0,1.0); }"); // load from memory

...

fs1.Start();

..

fs1.Stop();

fs2.Start();

..

fs2.Stop();

… and here is the whole class

 

class FragmentShader

{

private:

unsigned int fs,sp;



void CompileSrc(const char *src)

{

fs = glCreateShader(GL_FRAGMENT_SHADER);

glShaderSource(fs, 1, &src, NULL);

glCompileShader(fs);



int status = 0;

glGetShaderiv(fs, GL_COMPILE_STATUS, &status);

if (status==GL_FALSE)

{

char buffer[1024];

int loglen = 0;

glGetShaderInfoLog(fs, 1024, &loglen, buffer);

char buffer1[1024];

sprintf_s(buffer1, 1024, "Compiler error %s... while compiling:\n %s\n", buffer, src);

throw buffer1;

}



sp = glCreateProgram();

glAttachShader(sp, fs);

glLinkProgram(sp);

}



public:

FragmentShader(const char *src="", bool from_file=false) : fs(0), sp(0)

{

if (strlen(src)>0) Load(from_file,src);

}



void Load(bool from_file, const char* src="")

{

if (from_file)

{

std::ifstream file (src, std::ios::in|std::ios::binary|std::ios::ate);

if (file.is_open())

{

unsigned int size = file.tellg();

char *memblock = new char [size+1];



file.seekg (0, std::ios::beg);

file.read (memblock, size);

file.close();

memblock[size]=0;



CompileSrc(memblock);



delete [] memblock;

}

else

{

char buffer[1024];

sprintf_s(buffer, 1024, "Error opening: %s", src);

throw buffer;

}

}

else

{

CompileSrc(src);

}

}



void Start()

{

glUseProgram(sp);

}



void Stop()

{

glUseProgram(0);

}



~FragmentShader()

{

glDeleteShader(fs);

glDeleteProgram(sp);

}

};