Code Snippets
What's That?
I am using it actively
I planning to use/learn it
I don't plan to lean/use it
5th option
Home :: Programming :: Code Snippets :: OpenGL :: Drawing to a texture

[ Drawing to a texture ]

I am using OpenGL - like many other - because it is very straight forward and easy to use. Even complex operations can be done very easily and the code will never become really messy. And once again this can be proved when drawing a scene to an OpenGL texture. So why actually want to do something like that? There is one situation where this technique is very important. I assume everyone knows the "traditional" method of drawing reflections - flip matrix around reflection surface and draw object again. But what if the reflection surface is curved or simply not a normal plane. The answer: draw the scene to a texture and map it onto the curved surface. Easy, eh?

So let's quickly jump into the code. First we have to create an empty texture. Do this somewhere in your initialization code. The texture will be created using an empty colour array:

int xSize = 256, ySize = 256; //size of texture
//our OpenGL texture handle
unsigned int texture;
//new array
char* colorBits = new char[ xSize * ySize * 3 ];

//texture creation..

glTexImage2D(GL_TEXTURE_2D,0 ,3 , xSize,
	ySize, 0 , GL_RGB, 
	GL_UNSIGNED_BYTE, colorBits);

//you can set other texture parameters if you want

//clean up
delete[] colorBits;

Our texture is now created and ready to use. Note that the initial colour array isn't initialized because it doesn't matter as it will be overwritten later on. Now comes the interesting part. Before drawing to the texture, we will save the current viewport and change it to the size of the texture. Then we'll draw the scene that should fill the texture and we'll copy the scene colour data to the texture using glCopyTexImage2D(..). Last but not least we'll restore the old viewport. The code:

//save viewport and set up new one
int viewport[4];

//draw a misc scene

//save data to texture using glCopyTexImage2D

glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
   0,0, xSize, ySize, 0);

//restore viewport

Now we'll have our scene stored exactely in our texture. This texture can be used like any other texture loaded from file. glBindTexture(GL_TEXTURE, texture) will do the thing. If you want it even easier, try SRenderTexture from the code section. If you have questions, ask them in message board. Happy Coding!

 Last edited 2003-04-20 16:05:02 by André Stein - printable version
» copyright by andré stein
» using stCM v1.0
» steinsoft.net revision 5.0