5.3 - A Primer on Buffer Objects — LearnWebGL

文章推薦指數: 80 %
投票人數:10人

Buffer objects provide the data for attribute variables in vertex shader programs. Remember that WebGL is a restricted subset of OpenGL, and WebGL only ...   LearnWebGL TableofContents BookIndex 5.3-APrimeronBufferObjects¶ AbufferobjectisacontiguousblockofmemoryintheGPUthatcanbe accessedveryquicklybyshaderprogramsexecutingontheGPU.Bufferobjects storethedatathatshaderprogramsneedforrendering.Thecontentsofabuffer objectisalwaysan1-dimensionalarray.Forourpurposeswewillconsiderabufferobject toalwaysbehomogeneous-thatis,everyvaluewillhavethesamedatatype. (YoucanmixdatatypeswithsometrickyJavaScriptcode,butlet’skeepthingssimple.) Bufferobjectsprovidethedataforattributevariablesinvertex shaderprograms.RememberthatWebGLisarestrictedsubsetofOpenGL, andWebGLonlyallowsattributevariablestobeoftypefloat, vec2,vec3,vec4,mat2,mat3,and mat4.Theseareallfloatingpointvalues.Therefore,all bufferobjectsthatyoucreatewillbearraysoffloatingpointvalues. JavaScriptisnotastronglytypedlanguageanditdoesnotdistinguish betweendifferenttypesofnumbers.Mostprogramminglanguageshaveshorts,ints, floats,anddoubles.JavaScript’shasonlyonedatatypefornumericvalues: number.JavaScriptwasmodifiedtodealwithbinarydatavaluesbyadding “typedarray”objects.ForWebGL,allofyourbufferobjectswillcontain Float32Arrayarrays. //Floatingpointarrays. varf32=newFloat32Array(size);//Fractionalvalueswith7digitsofaccuracy Therearetwowaystoputdataintoa“typedarray”: IncludeanormalJavaScriptarrayofnumbersasaparametertotheconstructor. Createthearrayofacertainsizeandthensetindividualelementstospecificvalues. Thesetwooptionsaredemonstratedinthefollowingcode: //Createanarraycontaining6floats.Noticethebracketsaroundthearraydata. varmy_array=newFloat32Array([1.0,2.0,3.0,-1.0,-2.0,-3.0]); //Createanarraytohold4floatingpointnumbers. varan_array=newFloat32Array(4); an_array[0]=12.0; an_array[1]=5.0; an_array[2]=37.0; an_array[3]=18.3; CreatingandInitializingBufferObjects¶ NotethatbufferobjectsresideintheGPU,buttheyarecreated,managed, anddeletedusingtheWebGLAPIfromJavaScriptcode.Hereisatypical sequenceofcommandstocreateabufferobjectandfillitwithdata. //----------------------------------------------------------------------- functioncreateAndFillBufferObject(gl,data){ varbuffer_id; //Createabufferobject buffer_id=gl.createBuffer(); if(!buffer_id){ out.displayError('Failedtocreatethebufferobjectfor'+model_name); returnnull; } //Makethebufferobjecttheactivebuffer. gl.bindBuffer(gl.ARRAY_BUFFER,buffer_id); //UploadthedataforthisbufferobjecttotheGPU. gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW); returnbuffer_id; } Pleasenotethefollowingaboutthiscode: CreatinganobjectbufferdoesnothingmorethanreserveanewIDforanewbuffer. Youwilltypicallyhavemanyobjectbuffersandonlyoneofthemisthe “activebuffer”.Whenyouissuecommandsonbufferobjectsyouarealways manipulatingthe“activebuffer”.ThebindBufferfunctionsimplychanges the“activebuffer”tothespecificbufferusingthebuffer_id. ThebufferDatafunctioncopiesdatafromyourJavaScriptprogram intotheGPU’sbufferobject.Iftherewasalreadydatainthebufferobject thenitscurrentcontentsisdeletedandthenewdataisadded. ThemainerroryouwillreceivewhencopyingdatatotheGPUisOUT_OF_MEMORY. Thecodeaboveshouldcheckforglerrorsbycallinggl.getError(),but wewillworryaboutcatchingerrorslater. Shaders,Buffers,andtheGraphicsPipeline¶ Shaderprogramsaresometimesdifficultto“wrapyourbrainaround”because therelationshipbetweenthegraphicspipelineandashaderprogramisnot obviousandsometimesneverexplained.Let’strytowritesomepseudocodethat describeshowthegraphicspipelineperformsrendering. EachtimeyourJavaScriptprogramcallsgl.drawArrays(mode,start,count), ‘count’numberofverticesaresentthroughthegraphicspipeline. Yourvertexshaderprogramiscalledonceforeachvertexinanarrayof verticesthatisstoredinabufferobject. Insidethegraphicspipeline,hiddenfromyou,isaalgorithmthatisdoing this: for(j=start;j



請為這篇文章評分?