rts_glRenderToTexture.cpp 1.89 KB
#include "rts_glRenderToTexture.h"

void rts_glRenderToTexture::Clean()
{
	//clean up the fbo
	glDeleteFramebuffersEXT(1, &fbo);
	int num_tex = textures.size();

	//clean up all textures associated with the fbo
	for(int i=0; i<num_tex; i++)
		textures[i].Clean();
	textures.clear();

	fbo = 0;
}

void rts_glRenderToTexture::Init(int w, int h)
{
	CHECK_OPENGL_ERROR
	if(fbo != 0)
		Clean();
	CHECK_OPENGL_ERROR
	glGenFramebuffersEXT(1, &fbo);	//create the framebuffer object
	CHECK_OPENGL_ERROR
	width = w;
	height = h;

}

void rts_glRenderToTexture::AddTexture(GLenum target,
									   GLint internalformat,
									   GLenum format,
									   GLenum datatype,
									   GLint interpolation)
{

	//create the new texture
	rts_glTextureMap new_texture;
	new_texture.Init(NULL, 
					 target, 
					 width, 
					 height, 
					 0, 
					 internalformat, 
					 format, 
					 datatype,
					 interpolation);
	//push it into the texture vector
	textures.push_back(new_texture);
	cout<<"Texture Name: "<<new_texture.name<<endl;
	
	//bind it to the frame buffer
	
	glBindFramebufferEXT(GL_FRAMEBUFFER, fbo);
	CHECK_OPENGL_ERROR
	glFramebufferTexture2DEXT(GL_FRAMEBUFFER,
							  GL_COLOR_ATTACHMENT0 + textures.size() - 1,
							  target,
							  new_texture.name,
							  0);

	CHECK_OPENGL_ERROR
	GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER);
	CHECK_OPENGL_ERROR
	if(status != GL_FRAMEBUFFER_COMPLETE)
		cout<<"Framebuffer status invalid!"<<endl;

	//restore normal rendering
	glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
	
}

void rts_glRenderToTexture::BeginRender(int texture)
{
	
	//bind the framebuffer
	glBindFramebufferEXT(GL_FRAMEBUFFER, fbo);
	glDrawBuffer(GL_COLOR_ATTACHMENT0+texture);
}

void rts_glRenderToTexture::EndRender()
{
	//glFinish();
	//bind the screen buffer
	glBindFramebufferEXT(GL_FRAMEBUFFER, 0);
}