OpenGL Frame Buffer Object (FBO) - Song Ho Ahn
文章推薦指數: 80 %
Framebuffer is a collection of 2D arrays or storages utilized by OpenGL; colour buffers, depth buffer, stencil buffer and accumulation buffer. By default, ...
←Back
OpenGLFrameBufferObject(FBO)
RelatedTopics:PixelBufferObject(PBO)
Download:fbo.zip,fboDepth.zip,fboStencil.zip,fboBlit.zip,fboMsaa.zip,FrameBuffer.zip
Overview
CreatingFBO
RenderbufferObject
FBOwithMSAA(MultiSampleAntiAliasing)
CheckingFBOStatus
Example:RenderToTexture
FrameBufferC++Class
Update:FramebufferobjectextensionispromotedasacorefeatureofOpenGLversion3.0,andisapprovedbyARBcombiningthefollowingextensions;
EXT_framebuffer_object
EXT_framebuffer_blit
EXT_framebuffer_multisample
EXT_packed_depth_stencil
Overview
InOpenGLrenderingpipeline,thegeometrydataandtexturesaretransformedandpassedseveraltests,andthenfinallyrenderedontoascreenas2Dpixels.ThefinalrenderingdestinationoftheOpenGLpipelineiscalledframebuffer.Framebufferisacollectionof2DarraysorstoragesutilizedbyOpenGL;colourbuffers,depthbuffer,stencilbufferandaccumulationbuffer.Bydefault,OpenGLusestheframebufferasarenderingdestinationthatiscreatedandmanagedentirelybythewindowsystem.Thisdefaultframebufferiscalledwindow-system-providedframebuffer.
TheOpenGLextension,GL_ARB_framebuffer_objectprovidesaninterfacetocreateadditionalnon-displayableframebufferobjects(FBO).Thisframebufferiscalledapplication-createdframebufferinordertodistinguishfromthedefaultwindow-system-providedframebuffer.Byusingframebufferobject(FBO),anOpenGLapplicationcanredirecttherenderingoutputtotheapplication-createdframebufferobject(FBO)otherthanthetraditionalwindow-system-providedframebuffer.And,itisfullycontrolledbyOpenGL.
Similartowindow-system-providedframebuffer,aFBOcontainsacollectionofrenderingdestinations;color,depthandstencilbuffer.(NotethataccumulationbufferisnotdefinedinFBO.)TheselogicalbuffersinaFBOarecalledframebuffer-attachableimages,whichare2Darraysofpixelsthatcanbeattachedtoaframebufferobject.
Therearetwotypesofframebuffer-attachableimages;textureimagesandrenderbufferimages.Ifanimageofatextureobjectisattachedtoaframebuffer,OpenGLperforms"rendertotexture".Andifanimageofarenderbufferobjectisattachedtoaframebuffer,thenOpenGLperforms"offscreenrendering".
Bytheway,renderbufferobjectisanewtypeofstorageobjectdefinedinGL_ARB_framebuffer_objectextension.Itisusedasarenderingdestinationforasingle2Dimageduringrenderingprocess.
ConnectivitybetweenFBO,textureandRenderbuffer
Thefollowingdiagramshowstheconnectivityamongtheframebufferobject,textureobjectandrenderbufferobject.Multipletextureobjectsorrenderbufferobjectscanbeattachedtoaframebufferobjectthroughtheattachmentpoints.
Therearemultiplecolorattachmentpoints(GL_COLOR_ATTACHMENT0,...,GL_COLOR_ATTACHMENTn),onedepthattachmentpoint(GL_DEPTH_ATTACHMENT),andonestencilattachmentpoint(GL_STENCIL_ATTACHMENT)inaframebufferobject.Thenumberofcolorattachmentpointsisimplementationdependent,buteachFBOmusthaveatleastonecolorattachementpoint.YoucanquerythemaximumnumberofcolorattachementpointswithGL_MAX_COLOR_ATTACHMENTS,whicharesupportedbyagraphicscard.ThereasonthataFBOhasmultiplecolorattachementpointsistoallowtorenderthecolorbuffertomultipledestinationsatthesametime.This"multiplerendertargets"(MRT)canbeaccomplishedbyGL_ARB_draw_buffersextension.Noticethattheframebufferobjectitselfdoesnothaveanyimagestorage(array)init,but,ithasonlymultipleattachmentpoints.
Framebufferobject(FBO)providesanefficientswitchingmechanism;detachthepreviousframebuffer-attachableimagefromaFBO,andattachanewframebuffer-attachableimagetotheFBO.Switchingframebuffer-attachableimagesismuchfasterthanswitchingbetweenFBOs.FBOprovidesglFramebufferTexture2D()toswitch2Dtextureobjects,andglFramebufferRenderbuffer()toswitchrenderbufferobjects.
CreatingFrameBufferObject(FBO)
Creatingframebufferobjectsissimilartogeneratingvertexbufferobjects(VBO).
glGenFramebuffers()
voidglGenFramebuffers(GLsizein,GLuint*ids)
voidglDeleteFramebuffers(GLsizein,constGLuint*ids)
glGenFramebuffers()requires2parameters;thefirstoneisthenumberofframebufferstocreate,andthesecondparameteristhepointertoaGLuintvariableoranarraytostoreasingleIDormultipleIDs.ItreturnstheIDsofunusedframebufferobjects.ID0meansthedefaultframebuffer,whichisthewindow-system-providedframebuffer.
And,FBOmaybedeletedbycallingglDeleteFramebuffers()whenitisnotusedanymore.
glBindFramebuffer()
OnceaFBOiscreated,ithastobeboundbeforeusingit.
voidglBindFramebuffer(GLenumtarget,GLuintid)
Thefirstparameter,target,shouldbeGL_FRAMEBUFFER,andthesecondparameteristheIDofaframebufferobject.OnceaFBOisbound,allOpenGLoperationsaffectontothecurrentboundframebufferobject.TheobjectID0isreservedforthedefaultwindow-systemprovidedframebuffer.Therefore,inordertounbindthecurrentframebuffer(FBO),useID0inglBindFramebuffer().
RenderbufferObject
Inaddition,renderbufferobjectisnewlyintroducedforoffscreenrendering.Itallowstorenderascenedirectlytoarenderbufferobject,insteadofrenderingtoatextureobject.Renderbufferissimplyadatastorageobjectcontainingasingleimageofarenderableinternalformat.ItisusedtostoreOpenGLlogicalbuffersthatdonothavecorrespondingtextureformat,suchasstencilordepthbuffer.
glGenRenderbuffers()
voidglGenRenderbuffers(GLsizein,GLuint*ids)
voidglDeleteRenderbuffers(GLsizein,constGluint*ids)
Oncearenderbufferiscreated,itreturnsnon-zeropositiveinteger.ID0isreservedforOpenGL.
glBindRenderbuffer()
voidglBindRenderbuffer(GLenumtarget,GLuintid)
SameasotherOpenGLobjects,youhavetobindthecurrentrenderbufferobjectbeforereferencingit.ThetargetparametershouldbeGL_RENDERBUFFERforrenderbufferobject.
glRenderbufferStorage()
voidglRenderbufferStorage(GLenumtarget,
GLenuminternalFormat,
GLsizeiwidth,
GLsizeiheight)
Whenarenderbufferobjectiscreated,itdoesnothaveanydatastorage,sowehavetoallocateamemoryspaceforit.ThiscanbedonebyusingglRenderbufferStorage().ThefirstparametermustbeGL_RENDERBUFFER.Thesecondparameterwouldbecolor-renderable(GL_RGB,GL_RGBA,etc.),depth-renderable(GL_DEPTH_COMPONENT),orstencil-renderableformats(GL_STENCIL_INDEX).Thewidthandheightarethedimensionoftherenderbufferimageinpixels.
ThewidthandheightshouldbelessthanGL_MAX_RENDERBUFFER_SIZE,otherwise,itgeneratesGL_INVALID_VALUEerror.
glGetRenderbufferParameteriv()
voidglGetRenderbufferParameteriv(GLenumtarget,
GLenumparam,
GLint*value)
Youalsogetvariousparametersofthecurrentlyboundrenderbufferobject.targetshouldbeGL_RENDERBUFFER,andthesecondparameteristhenameofparameter.Thelastisthepointertoanintegervariabletostorethereturnedvalue.Theavailablenamesoftherenderbufferparametersare;
GL_RENDERBUFFER_WIDTH
GL_RENDERBUFFER_HEIGHT
GL_RENDERBUFFER_INTERNAL_FORMAT
GL_RENDERBUFFER_RED_SIZE
GL_RENDERBUFFER_GREEN_SIZE
GL_RENDERBUFFER_BLUE_SIZE
GL_RENDERBUFFER_ALPHA_SIZE
GL_RENDERBUFFER_DEPTH_SIZE
GL_RENDERBUFFER_STENCIL_SIZE
AttachingimagestoFBO
FBOitselfdoesnothaveanyimagestorage(buffer)init.Instead,wemustattachframebuffer-attachableimages(textureorrenderbufferobjects)totheFBO.ThismechanismallowsthatFBOquicklyswitch(detachandattach)theframebuffer-attachableimagesinaFBO.Itismuchfastertoswitchframebuffer-attachableimagesthantoswitchbetweenFBOs.And,itsavesunnecessarydatacopiesandmemoryconsumption.Forexample,atexturecanbeattachedtomultipleFBOs,anditsimagestoragecanbesharedbymultipleFBOs.
Attachinga2DtextureimagetoFBO
glFramebufferTexture2D(GLenumtarget,
GLenumattachmentPoint,
GLenumtextureTarget,
GLuinttextureId,
GLintlevel)
glFramebufferTexture2D()istoattacha2DtextureimagetoaFBO.ThefirstparametermustbeGL_FRAMEBUFFER,andthesecondparameteristheattachmentpointwheretoconnectthetextureimage.AFBOhasmultiplecolorattachmentpoints(GL_COLOR_ATTACHMENT0,...,GL_COLOR_ATTACHMENTn),GL_DEPTH_ATTACHMENT,andGL_STENCIL_ATTACHMENT.Thethirdparameter,"textureTarget"isGL_TEXTURE_2Dinmostcases.Thefourthparameteristheidentifierofthetextureobject.Thelastparameteristhemipmaplevelofthetexturetobeattached.
IfthetextureIdparameterissetto0,then,thetextureimagewillbedetachedfromtheFBO.IfatextureobjectisdeletedwhileitisstillattachedtoaFBO,then,thetextureimagewillbeautomaticallydetachedfromthecurrentlyboundFBO.However,ifitisattachedtomultipleFBOsanddeleted,thenitwillbedetachedfromonlytheboundFBO,butwillnotbedetachedfromanyotherun-boundFBOs.
AttachingaRenderbufferimagetoFBO
voidglFramebufferRenderbuffer(GLenumtarget,
GLenumattachmentPoint,
GLenumrenderbufferTarget,
GLuintrenderbufferId)
ArenderbufferimagecanbeattachedbycallingglFramebufferRenderbuffer().ThefirstandsecondparametersaresameasglFramebufferTexture2D().ThethirdparametermustbeGL_RENDERBUFFER,andthelastparameteristheIDoftherenderbufferobject.
IfrenderbufferIdparameterissetto0,therenderbufferimagewillbedetachedfromtheattachmentpointintheFBO.IfarenderbufferobjectisdeletedwhileitisstillattachedinaFBO,thenitwillbeautomaticallydetachedfromtheboundFBO.However,itwillnotbedetachedfromanyothernon-boundFBOs.
FBOwithMSAA(MultiSampleAntiAliasing)
Comparison:NoAnti-aliasingvs.MSAA
WhenyourendertoaFBO,anti-aliasingisnotautomaticallyenabledevenifyouproperlycreateaOpenGLrenderingcontextwiththemultisamplingattribute(SAMPLEBUFFERS_ARB)forwindow-system-providedframebuffer.
Inordertoactivatemultisampleanti-aliasingmodeforrenderingtoaFBO,youneedtoprepareandattachmultisampleimagestoaFBO'scolorand/ordepthattachementpoints.
FBOextensionprovidesglRenderbufferStorageMultisample()tocreatearenderbufferimageformultisampleanti-aliasingrenderingmode.
voidglRenderbufferStorageMultisample(GLenumtarget,
GLsizeisamples,
GLenuminternalFormat,
GLsizeiwidth,
GLsizeiheight)
Itaddsnewparameter,samplesontopofglRenderbufferStorage(),whichisthenumberofmultisamplesforanti-aliasedrenderingmode.Ifitis0,thennoMSAAmodeisenabledandglRenderbufferStorage()iscalledinstead.YoucanquerythemaximumnumberofsampleswithGL_MAX_SAMPLEStokeninglGetIntegerv().
ThefollowingcodeistocreateaFBOwithmultisamplecolorbufferanddepthbufferimages.NotethatifmultipleimagesareattachedtoaFBO,thenallimagesmusthavethesamenumberofmultisamples.Otherwise,theFBOstatusisincomplete.
//createa4xMSAArenderbufferobjectforcolorbuffer
intmsaa=4;
GLuintrboColorId;
glGenRenderbuffers(1,&rboColorId);
glBindRenderbuffer(GL_RENDERBUFFER,rboColorId);
glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_RGBA8,width,height);
//createa4xMSAArenderbufferobjectfordepthbuffer
GLuintrboDepthId;
glGenRenderbuffers(1,&rboDepthId);
glBindRenderbuffer(GL_RENDERBUFFER,rboDepthId);
glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_DEPTH_COMPONENT,width,height);
//createa4xMSAAframebufferobject
GLuintfboMsaaId;
glGenFramebuffers(1,&fboMsaaId);
glBindFramebuffer(GL_FRAMEBUFFER,fboMsaaId);
//attachcolorbufferimagetoFBO
glFramebufferRenderbuffer(GL_FRAMEBUFFER,//1.fbotarget:GL_FRAMEBUFFER
GL_COLOR_ATTACHMENT0,//2.colorattachmentpoint
GL_RENDERBUFFER,//3.rbotarget:GL_RENDERBUFFER
rboColorId);//4.rboID
//attachdepthbufferimagetoFBO
glFramebufferRenderbuffer(GL_FRAMEBUFFER,//1.fbotarget:GL_FRAMEBUFFER
GL_DEPTH_ATTACHMENT,//2.depthattachmentpoint
GL_RENDERBUFFER,//3.rbotarget:GL_RENDERBUFFER
rboDepthId);//4.rboID
//checkFBOstatus
GLenumstatus=glCheckFramebufferStatus(GL_FRAMEBUFFER);
if(status!=GL_FRAMEBUFFER_COMPLETE)
fboUsed=false;
ItisimportanttoknowthatglRenderbufferStorageMultisample()onlyenablesMSAArenderingtoFBO.However,youcannotdirectlyusetheresultfromMSAAFBO.Ifyouneedtotransfertheresulttoatextureorothernon-multisampledframebuffer,youhavetoconvert(downsample)theresulttosingle-sampleimageusingglBlitFramebuffer().
voidglBlitFramebuffer(GLintsrcX0,GLintsrcY0,GLintsrcX1,GLintsrcY1,//sourcerectangle
GLintdstX0,GLintdstY0,GLintdstX1,GLintdstY1,//destinationrect
GLbitfieldmask,
GLenumfilter)
glBlitFramebuffer()copiesarectangleofimagesfromthesource(GL_READ_BUFFER)tothedestinationframebuffer(GL_DRAW_BUFFER).The"mask"parameteristospecifywhichbuffersarecopied,GL_COLOR_BUFFER_BIT,GL_DEPTH_BUFFER_BITand/orGL_STENCIL_BUFFER_BIT.Thelastparameter,"filter"istospecifytheinterpolationmodeifthesourceanddestinationrectanglesarenotsamedimension.ItiseitherGL_NEARESTorGL_LINEAR.
ThefollowingcodeistotransferamultisampledimagefromaFBOtoanothernon-multisampledFBO.NoticeitrequiresanadditionalFBOtogettheresultofMSAArendering.PleaseseefboMsaa.zipfordetailstoperformrender-to-texturewithMSAA.
//copyrenderedimagefromMSAA(multi-sample)tonormal(single-sample)
//NOTE:Themultisamplesatapixelinreadbufferwillbeconverted
//toasinglesampleatthetargetpixelindrawbuffer.
glBindFramebuffer(GL_READ_FRAMEBUFFER,fboMsaaId);//srcFBO(multi-sample)
glBindFramebuffer(GL_DRAW_FRAMEBUFFER,fboId);//dstFBO(single-sample)
glBlitFramebuffer(0,0,width,height,//srcrect
0,0,width,height,//dstrect
GL_COLOR_BUFFER_BIT,//buffermask
GL_LINEAR);//scalefilter
CheckingFBOStatus
Onceattachableimages(texturesandrenderbuffers)areattachedtoaFBOandbeforeperformingFBOoperation,youmustvalidateiftheFBOstatusiscompleteorincompletebyusingglCheckFramebufferStatus().IftheFBOisnotcomplete,thenanydrawingandreadingcommand(glBegin(),glCopyTexImage2D(),etc)willbefailed.
GLenumglCheckFramebufferStatus(GLenumtarget)
glCheckFramebufferStatus()validatesallitsattachedimagesandframebufferparametersonthecurrentlyboundFBO.And,thisfunctioncannotbecalledwithinglBegin()/glEnd()pair.ThetargetparametershouldbeGL_FRAMEBUFFER.Itreturnsnon-zerovalueaftercheckingtheFBO.Ifallrequirementsandrulesaresatisfied,thenitreturnsGL_FRAMEBUFFER_COMPLETE.Otherwise,itreturnsarelevanterrorvalue,whichtellswhatruleisviolated.
TherulesofFBOcompletenessare:
Thewidthandheightofframebuffer-attachableimagemustbenotzero.
Ifanimageisattachedtoacolorattachmentpoint,thentheimagemusthaveacolor-renderableinternalformat.(GL_RGBA,GL_DEPTH_COMPONENT,GL_LUMINANCE,etc)
IfanimageisattachedtoGL_DEPTH_ATTACHMENT,thentheimagemusthaveadepth-renderableinternalformat.(GL_DEPTH_COMPONENT,GL_DEPTH_COMPONENT24,etc)
IfanimageisattachedtoGL_STENCIL_ATTACHMENT,thentheimagemusthaveastencil-renderableinternalformat.(GL_STENCIL_INDEX,GL_STENCIL_INDEX8,etc)
FBOmusthaveatleastoneimageattached.
AllimagesattachedaFBOmusthavethesamewidthandheight.
Allimagesattachedthecolorattachmentpointsmusthavethesameinternalformat.
Notethateventhoughalloftheaboveconditionsaresatisfied,yourOpenGLdrivermaynotsupportsomecombinationsofinternalformatsandparameters.IfaparticularimplementationisnotsupportedbyOpenGLdriver,thenglCheckFramebufferStatus()returnsGL_FRAMEBUFFER_UNSUPPORTED.
ThesamplecodeprovidessomeutilityfunctionstoreporttheinformationofthecurrentFBO;printFramebufferInfo()andcheckFramebufferStatus().
Example:RenderToTexture
Downloadthesourceandbinary:fbo.zip(Updated:2020-05-07)
Extras:
-Renderingtothedepthbufferonly:fboDepth.zip
-Renderingtheoutlinesofanobjectusingstencilbuffer:fboStencil.zip
-Blitingbetween2FBOsusingglBlitFramebuffer():fboBlit.zip
-RenderingtotexturewithMSAA:fboMsaa.zip
-RenderingtotexturewithFrameBufferC++class:FrameBuffer.zip(Updated:2022-05-22)
Sometimes,youneedtogeneratedynamictexturesonthefly.Themostcommonexamplesaregeneratingmirroring/reflectioneffects,dynamiccube/environmentmapsandshadowmaps.Dynamictexturingcanbeaccomplishedbyrenderingthescenetoatexture.Atraditionalwayofrender-to-textureistodrawascenetotheframebufferasnormal,andthencopytheframebufferimagetoatexturebyusingglCopyTexSubImage2D().
UsingFBO,wecanrenderascenedirectlyontoatexture,sowedon'thavetousethewindow-system-providedframebufferatall.Furthermore,wecaneliminateanadditionaldatacopy(fromframebuffertotexture).
Thisdemoprogramperformsrendertotextureoperationwith/withoutFBO,andcomparestheperformancedifference.Otherthanperformancegain,thereisanotheradvantageofusingFBO.Ifthetextureresolutionislargerthanthesizeoftherenderingwindowintraditionalrender-to-texturemode(withoutFBO),thentheareaoutofthewindowregionwillbeclipped.However,FBOdoesnotsufferfromthisclippingproblem.Youcancreateaframebuffer-renderableimagelargerthanthedisplaywindow.
ThefollowingcodesistosetupaFBOandframebuffer-attachableimagesbeforetherenderingloopisstarted.NotethatnotonlyatextureimageisattachedtotheFBO,butalso,arenderbufferimageisattachedtothedepthattachmentpointoftheFBO.Wedonotactuallyusethisdepthbuffer,however,theFBOitselfneedsitfordepthtest.Ifwedon'tattachthisdepthrenderableimagetotheFBO,thentherenderingoutputwillbecorruptedbecauseofmissingdepthtest.IfstenciltestisalsorequiredduringFBOrendering,thenadditionalrenderbufferimageshouldbeattachedtoGL_STENCIL_ATTACHMENT.
...
//createatextureobject
GLuinttextureId;
glGenTextures(1,&textureId);
glBindTexture(GL_TEXTURE_2D,textureId);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
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_GENERATE_MIPMAP,GL_TRUE);//automaticmipmap
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA8,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,0);
glBindTexture(GL_TEXTURE_2D,0);
//createarenderbufferobjecttostoredepthinfo
GLuintrboId;
glGenRenderbuffers(1,&rboId);
glBindRenderbuffer(GL_RENDERBUFFER,rboId);
glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH_COMPONENT,width,height);
glBindRenderbuffer(GL_RENDERBUFFER,0);
//createaframebufferobject
GLuintfboId;
glGenFramebuffers(1,&fboId);
glBindFramebuffer(GL_FRAMEBUFFER,fboId);
//attachthetexturetoFBOcolorattachmentpoint
glFramebufferTexture2D(GL_FRAMEBUFFER,//1.fbotarget:GL_FRAMEBUFFER
GL_COLOR_ATTACHMENT0,//2.attachmentpoint
GL_TEXTURE_2D,//3.textarget:GL_TEXTURE_2D
textureId,//4.texID
0);//5.mipmaplevel:0(base)
//attachtherenderbuffertodepthattachmentpoint
glFramebufferRenderbuffer(GL_FRAMEBUFFER,//1.fbotarget:GL_FRAMEBUFFER
GL_DEPTH_ATTACHMENT,//2.attachmentpoint
GL_RENDERBUFFER,//3.rbotarget:GL_RENDERBUFFER
rboId);//4.rboID
//checkFBOstatus
GLenumstatus=glCheckFramebufferStatus(GL_FRAMEBUFFER);
if(status!=GL_FRAMEBUFFER_COMPLETE)
fboUsed=false;
//switchbacktowindow-system-providedframebuffer
glBindFramebuffer(GL_FRAMEBUFFER,0);
...
Therenderingprocedureofrender-to-textureisalmostsameasnormaldrawing.Weonlyneedtoswitchtherenderingdestinationfromthewindow-system-providedtothenon-displayable,application-createdframebuffer(FBO).
...
//setrenderingdestinationtoFBO
glBindFramebuffer(GL_FRAMEBUFFER,fboId);
//clearbuffers
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
//drawascenetoatexturedirectly
draw();
//unbindFBO
glBindFramebuffer(GL_FRAMEBUFFER,0);
//triggermipmapsgenerationexplicitly
//NOTE:IfGL_GENERATE_MIPMAPissettoGL_TRUE,thenglCopyTexSubImage2D()
//triggersmipmapgenerationautomatically.However,thetextureattached
//ontoaFBOshouldgeneratemipmapsmanuallyviaglGenerateMipmap().
glBindTexture(GL_TEXTURE_2D,textureId);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,0);
...
NotethatglGenerateMipmap()isalsoincludedaspartofFBOextensioninordertogeneratemipmapsexplicitlyaftermodifyingthebaseleveltextureimage.IfGL_GENERATE_MIPMAPissettoGL_TRUE,thenglTex{Sub}Image2D()andglCopyTex{Sub}Image2D()triggerautomaticmipmapgeneration(inOpenGLversion1.4orgreater).However,FBOoperationdoesnotgenerateitsmipmapsautomaticallywhenthebaseleveltextureismodifiedbecauseFBOdoesnotcallglCopyTex{Sub}Image2D()tomodifythetexture.Therefore,glGenerateMipmap()mustbeexplicitlycalledformipmapgeneration.
Ifyouneedtoapostprocessingofthetexture,itispossibletocombinewithPixelBufferObject(PBO)tomodifythetextureefficiently.
FrameBufferC++Class
ItisanexampleofC++wrapperclasshowtoencapsulateanOpenGLframebufferobject,anditsassociatedcolorbuffer(textureobject)anddepthbuffer(renderbufferobject)intoaC++class.Italsoprovidessimplebutconvenientinterfacestocontroltheframebufferobject.ThefollowingC++codesnippetiscreationandusageofFrameBufferC++class.And,seemoredetailsinFrameBuffer.cppfile.(Updated:2022-05-22)
//initializeFBOwithwidth,heightandmsaa
FrameBufferfbo;
fbo.init(width,height);//forsingle-sampleFBO
fbo.init(width,height,msaa);//formulti-sampleFBO,msaa=2,4,8...
...
//checkcompletenessanderror
std::cout<
延伸文章資訊
- 1OpenGL幀快取物件(FBO:Frame Buffer Object) - 程式人生
在OpenGL渲染管線中,幾何資料和紋理經過多次轉化和多次測試,最後以二維畫素的形式顯示在螢幕上。OpenGL管線的最終渲染目的地被稱作幀快取(framebuffer ...
- 2帧缓冲 - LearnOpenGL-CN
把这几种缓冲结合起来叫做帧缓冲(Framebuffer),它被储存于内存中。OpenGL给了我们自己定义帧缓冲的自由,我们可以选择性的定义自己的颜色缓冲、深度和模板缓冲。
- 3Framebuffers - LearnOpenGL
Renderbuffer objects were introduced to OpenGL after textures as a possible type of framebuffer a...
- 4【OpenGL】OpenGL帧缓存对象(FBO:Frame Buffer Object)
OpenGL管线的最终渲染目的地被称作帧缓存(framebuffer)。帧缓冲是一些二维数组和OpenG所使用的存储区的集合:颜色缓存、深度缓存、模板缓存和累计缓存。
- 5帧缓冲
和OpenGL中的其它对象一样,我们会使用一个叫做 glGenFramebuffers 的函数来创建一个帧缓冲对象(Framebuffer Object, FBO): unsigned int ...