PDA

View Full Version : Render To Texture with OpenGL



lassad
16-11-2022, 11:17
Hi
I noteced that TBGL lacks render to texture functions. this is a simple way to do it using the fastest way.

first we must setup OGL to draw in 2D

// the main function = puts the texture we want to render to on backbuffer
Void BeginRTT(void* tosp){
glDisable(GL_FOG);
glDisable(GL_LIGHTING);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

glClearColor(0.0,0.0,0.0,0); // Black Background
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer

glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,TEXTUREID(tosp)); // TEXTUREID is a function that returns the opengl number of the texture

glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, W,0,H,0, -1); // W and H are the window width and height
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

glColor4f(1,1,1,1);
float tx1=0;
float tx2=TextureWidth(tosp);
float ty2=TextureHeight(tosp);
float ty1=0;
glBegin(GL_QUADS);
glTexCoord2f(0,0);
glVertex2i(tx1,ty1);
glTexCoord2f(0,1);
glVertex2f(tx1,ty2);
glTexCoord2f(1,1);
glVertex2f(tx2,ty2);
glTexCoord2f(1,0);
glVertex2f(tx2,ty1);
glEnd();

// these are global variables to backup the last call of BeginRTT in order to use them in EndRTT function
LastRTT=TextureID(tosp);
LastRTT_H=TextureHeight(tosp);
LastRTT_W=TextureWidth(tosp);
}

now we can draw 2D stuff on the screen , sprites, fonts... remember to call EndRTT just after.

void EndRTT(){
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,LastRTT);
glTexParameteri(GL_TEXTURE_2D,GL_GENERATE_MIPMAP,GL_TRUE);
glCopyTexSubImage2D(GL_TEXTURE_2D,0, 0,0,0,0,LastRTT_W,LastRTT_H); // Fastest way to Copy backbuffer to texture
glDisable(GL_TEXTURE_2D);
glClearColor(0.0,0.0,0.0,0); // Black Background
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glColor4ub(255,255,255,255);
glEnable(GL_LIGHTING);
}

Now your texture contains every thing you Drew ..

this is how i do it in C++, if some body can translate it to thinbasic or integrate it in TBGL .

Hope it can be useful.

Petr Schreiber
19-11-2022, 11:16
Thank you very much for sharing your solution!

There is a built in function called TBGL_RenderToTexture which should be of use, demonstrated here:
SampleScripts\TBGL\EntityBased\TBGL_MotionBlur.tbasic

Should you need to render to bigger-than-screen canvas, I prepared this solution on gitHub:
https://github.com/petrSchreiber/offScreenRenderer


Petr