#include <stdio.h>
#include <stdlib.h>
#define GL_GLEXT_PROTOTYPES
#include <GL/GLee.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <vector>
#include <stack>
class RenderToTexture
{
public:
RenderToTexture();
~RenderToTexture();
void start();
unsigned int finish();
unsigned int texture;
protected:
private:
unsigned int frameBuffer;
};
RenderToTexture::RenderToTexture()
{
//ctor
glGenFramebuffersEXT(1, &frameBuffer);
glGenTextures(1, &texture);
}
RenderToTexture::~RenderToTexture()
{
//dtor
glDeleteFramebuffersEXT(1,&frameBuffer);
}
void RenderToTexture::start()
{
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 90, 90, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, frameBuffer);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, texture, 0);
if (glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) != GL_FRAMEBUFFER_COMPLETE_EXT)
{
printf("error
");
}
}
unsigned int RenderToTexture::finish()
{
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
return texture;
}
void checkGLError( const char hdr[] )
{
int err = glGetError();
if( err )
{
fprintf(stderr, "ERROR %s: %s
", hdr, gluErrorString(err));
exit(1);
}
}
void reshape(GLsizei w, GLsizei h)
{
glViewport(0, 0, w, h);
glutPostRedisplay();
}
void keyboard( unsigned char key, int x, int y )
{
// Key Bindings
switch( key )
{
case 27 : exit(0); break;
}
}
void renderQuad()
{
glBegin(GL_QUADS);
glTexCoord2f(0,0);glVertex2f(0,0);
glTexCoord2f(0,1);glVertex2f(0,30);
glTexCoord2f(1,1);glVertex2f(30,30);
glTexCoord2f(1,0);glVertex2f(30,0);
glEnd();
}
RenderToTexture* rtt;
void display()
{
glClearColor( 0,0,1,1 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glColor3f(1,0,0);
glDisable(GL_TEXTURE_2D);
rtt->start();
renderQuad(); // Creates a texture with a square cut out of the corner
glBindTexture(GL_TEXTURE_2D,rtt->finish());
glEnable(GL_TEXTURE_2D);
glColor3f(0,1,0);
renderQuad();// Tries to render a square in the corner with the texture on it
glutSwapBuffers();
checkGLError( “display() end” );
}
main( int argc, char *argv[] )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_DOUBLE | GLUT_DEPTH | GLUT_RGB );
glutCreateWindow( “window title” );
checkGLError( “Create window” );
glutReshapeFunc ( reshape );
glutDisplayFunc ( display );
glutKeyboardFunc( keyboard );
rtt = new RenderToTexture;
glutPostRedisplay();
glutMainLoop();
}