OpenGL: Render to Texture


  

An example:

glewInit();

 

///generate a texture

glGenTextures(1,&tex);

glBindTexture(GL_TEXTURE_2D,tex);    

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);

/// automatic mipmap generation

glTexParameteri(GL_TEXTURE_2D,GL_GENERATE_MIPMAP,GL_TRUE);

glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,texturewidth,textureheight,0,GL_RGBA,GL_UNSIGNED_BYTE,0);

glEnable(GL_TEXTURE_2D);

 

///generate a render buffer

glGenRenderbuffers(1,&renderbuffer);

glBindRenderbuffer(GL_RENDERBUFFER,renderbuffer);

glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH_COMPONENT24,texturewidth,textureheight);

  

/generate a framebuffer with attachment to a texture

glGenFramebuffers(1,&fbo);

glBindFramebuffer(GL_FRAMEBUFFER,fbo);

//attach the texture

glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,texure-name,0);

glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,renderbuffer);

open the depth test

glEnable(GL_DEPTH_TEST);

 

The code above is a preparation for the following render.

 

glBindTexture(GL_TEXTURE_2D,0);

//use the framebuffer created by application

glBindFramebuffer(GL_FRAMEBUFFER,fbo);

glClearColor(0,0,0,1.0);

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

 

/do all your render here

/

/

glBindFramebuffer(GL_FRAMEBUFFER,0);

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

  

// It should be set to 1, for why?

glColor3f(1.0,1.0,1.0);

glBindTexture(GL_TEXTURE_2D,texture-name);

glGenerateMipmap(GL_TEXTURE_2D);

do other render with the texture

/

/

if we want to modify the texture  we can do as follow

/

glBindFramebuffer(GL_FRAMEBUFFER,fbo);

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

/modify it here

glBindFramebuffer(GL_FRAMEBUFFER,0);

glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

glColor3f(1.0,1.0,1.0);

 

glBindTexture(GL_TEXTURE_2D,tex);

glGenerateMipmap(GL_TEXTURE_2D);

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值