WebGLRenderingContext.vertexAttribPointer() - Web APIs
文章推薦指數: 80 %
The WebGLRenderingContext.vertexAttribPointer() method of the WebGL API binds the buffer currently bound to gl.ARRAY_BUFFER to a generic ...
SkiptomaincontentSkiptosearchSkiptoselectlanguageReferencesWebAPIsWebGLRenderingContextWebGLRenderingContext.vertexAttribPointer()ArticleActionsEnglish(US)SyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoRelatedTopicsWebGLAPIWebGLRenderingContextPropertiescanvasdrawingBufferHeightdrawingBufferWidthMethodsactiveTexture()attachShader()bindAttribLocation()bindBuffer()bindFramebuffer()bindRenderbuffer()bindTexture()blendColor()blendEquation()blendEquationSeparate()blendFunc()blendFuncSeparate()bufferData()bufferSubData()checkFramebufferStatus()clear()clearColor()clearDepth()clearStencil()colorMask()
Experimental
commit()compileShader()compressedTexImage[23]D()compressedTexSubImage2D()copyTexImage2D()copyTexSubImage2D()createBuffer()createFramebuffer()createProgram()createRenderbuffer()createShader()createTexture()cullFace()deleteBuffer()deleteFramebuffer()deleteProgram()deleteRenderbuffer()deleteShader()deleteTexture()depthFunc()depthMask()depthRange()detachShader()disable()disableVertexAttribArray()drawArrays()drawElements()enable()enableVertexAttribArray()finish()flush()framebufferRenderbuffer()framebufferTexture2D()frontFace()generateMipmap()getActiveAttrib()getActiveUniform()getAttachedShaders()getAttribLocation()getBufferParameter()getContextAttributes()getError()getExtension()getFramebufferAttachmentParameter()getParameter()getProgramInfoLog()getProgramParameter()getRenderbufferParameter()getShaderInfoLog()getShaderParameter()getShaderPrecisionFormat()getShaderSource()getSupportedExtensions()getTexParameter()getUniform()getUniformLocation()getVertexAttrib()getVertexAttribOffset()hint()isBuffer()isContextLost()isEnabled()isFramebuffer()isProgram()isRenderbuffer()isShader()isTexture()lineWidth()linkProgram()makeXRCompatible()pixelStorei()polygonOffset()readPixels()renderbufferStorage()sampleCoverage()scissor()shaderSource()stencilFunc()stencilFuncSeparate()stencilMask()stencilMaskSeparate()stencilOp()stencilOpSeparate()texImage2D()texParameter[fi]()texSubImage2D()uniform[1234][fi][v]()uniformMatrix[234]fv()useProgram()validateProgram()vertexAttrib[1234]f[v]()vertexAttribPointer()viewport()RelatedpagesforWebGLANGLE_instanced_arraysEXT_blend_minmaxEXT_color_buffer_half_floatEXT_disjoint_timer_queryEXT_frag_depthEXT_sRGBEXT_shader_texture_lodEXT_texture_filter_anisotropicOES_element_index_uintOES_standard_derivativesOES_texture_floatOES_texture_float_linearOES_texture_half_floatOES_texture_half_float_linearOES_vertex_array_objectWEBGL_color_buffer_floatWEBGL_compressed_texture_etc1WEBGL_compressed_texture_pvrtcWEBGL_compressed_texture_s3tcWEBGL_compressed_texture_s3tc_srgbWEBGL_debug_renderer_infoWEBGL_debug_shadersWEBGL_depth_textureWEBGL_draw_buffersWEBGL_lose_contextWebGL2RenderingContextWebGLActiveInfoWebGLBufferWebGLContextEventWebGLFramebufferWebGLObjectWebGLProgramWebGLQueryWebGLRenderbufferWebGLSamplerWebGLShaderWebGLShaderPrecisionFormatWebGLSyncWebGLTextureWebGLTransformFeedbackWebGLUniformLocationWebGLVertexArrayObjectSyntaxDescriptionExamplesSpecificationsBrowsercompatibilitySeealsoWebGLRenderingContext.vertexAttribPointer()
The
WebGLRenderingContext.vertexAttribPointer()methodofthe
WebGLAPIbindsthebuffercurrentlybound
togl.ARRAY_BUFFERtoagenericvertexattributeofthecurrentvertex
bufferobjectandspecifiesitslayout.
SyntaxvertexAttribPointer(index,size,type,normalized,stride,offset)
Parameters
index
AGLuintspecifyingtheindexofthevertexattributethatistobe
modified.
size
AGLintspecifyingthenumberofcomponentspervertexattribute.
Mustbe1,2,3,or4.
type
AGLenumspecifyingthedatatypeofeachcomponentinthearray.
Possiblevalues:
gl.BYTE:signed8-bitinteger,withvaluesin[-128,127]
gl.SHORT:signed16-bitinteger,withvaluesin[-32768,32767]
gl.UNSIGNED_BYTE:unsigned8-bitinteger,withvaluesin[0,255]
gl.UNSIGNED_SHORT:unsigned16-bitinteger,withvaluesin[0,
65535]
gl.FLOAT:32-bitIEEEfloatingpointnumber
WhenusingaWebGL2context,
thefollowingvaluesareavailableadditionally:
gl.HALF_FLOAT:16-bitIEEEfloatingpointnumber
normalized
AGLbooleanspecifyingwhetherintegerdatavaluesshouldbe
normalizedintoacertainrangewhenbeingcasttoafloat.
Fortypesgl.BYTEandgl.SHORT,normalizesthevalues
to[-1,1]iftrue.
Fortypesgl.UNSIGNED_BYTEandgl.UNSIGNED_SHORT,
normalizesthevaluesto[0,1]iftrue.
Fortypesgl.FLOATandgl.HALF_FLOAT,thisparameter
hasnoeffect.
stride
AGLsizeispecifyingtheoffsetinbytesbetweenthebeginningof
consecutivevertexattributes.Cannotbelargerthan255.Ifstrideis0,the
attributeisassumedtobetightlypacked,thatis,theattributesarenotinterleaved
buteachattributeisinaseparateblock,andthenextvertex'attributefollows
immediatelyafterthecurrentvertex.
offset
AGLintptrspecifyinganoffsetinbytesofthefirstcomponentin
thevertexattributearray.Mustbeamultipleofthebytelength
oftype.
ReturnvalueNone(undefined).Exceptions
Agl.INVALID_VALUEerroristhrownifoffsetisnegative.
Agl.INVALID_OPERATIONerroristhrownifstrideand
offsetarenotmultiplesofthesizeofthedatatype.
Agl.INVALID_OPERATIONerroristhrownifnoWebGLBufferisboundto
theARRAY_BUFFERtarget.
WhenusingaWebGL2context,a
gl.INVALID_OPERATIONerroristhrownifthisvertexattributeisdefined
asaintegerinthevertexshader(e.g.uvec4orivec4,
insteadofvec4).
Description
Let'sassumewewanttorendersome3Dgeometry,andforthatwewillneedtosupply
ourverticestotheVertexShader.Eachvertexhasafewattributes,likeposition,
normalvector,ortexturecoordinate,thataredefinedinanArrayBuffer
andwillbesuppliedtotheVertexBufferObject(VBO).First,weneedtobindthe
WebGLBufferwewanttousetogl.ARRAY_BUFFER,then,with
thismethod,gl.vertexAttribPointer(),wespecifyinwhatorderthe
attributesarestored,andwhatdatatypetheyarein.Inaddition,weneedtoinclude
thestride,whichisthetotalbytelengthofallattributesforonevertex.Also,we
havetocallgl.enableVertexAttribArray()totellWebGLthatthisattributeshouldbefilled
withdatafromourarraybuffer.
Usually,your3Dgeometryisalreadyinacertainbinaryformat,soyouneedtoread
thespecificationofthatspecificformattofigureoutthememorylayout.However,if
youaredesigningtheformatyourself,oryourgeometryisintextfiles(likeWavefront.objfiles)and
mustbeconvertedintoanArrayBufferatruntime,youhavefreechoiceon
howtostructurethememory.Forhighestperformance,interleavetheattributes
andusethesmallestdatatypethatstillaccuratelyrepresentsyourgeometry.
Themaximumnumberofvertexattributesdependsonthegraphicscard,andyoucancall
gl.getParameter(gl.MAX_VERTEX_ATTRIBS)togetthisvalue.Onhigh-end
graphicscards,themaximumis16,onlower-endgraphicscards,thevaluewillbelower.
Attributeindex
Foreachattribute,youmustspecifyitsindex.Thisisindependentfromthelocation
insidethearraybuffer,soyourattributescanbesentinadifferentorderthanhow
theyarestoredinthearraybuffer.Youhavetwooptions:
Eitheryouspecifytheindexyourself.Inthiscase,youcall
gl.bindAttribLocation()
toconnectanamedattributefromthevertexshadertotheindexyouwanttouse.This
mustbedonebeforecallinggl.linkProgram().Youcanthenprovidethissameindexto
gl.vertexAttribPointer().
Alternatively,youusetheindexthatisassignedbythegraphicscardwhen
compilingthevertexshader.Dependingonthegraphicscard,theindexwillvary,so
youmustcallgl.getAttribLocation()tofindouttheindex,andthenprovidethisindexto
gl.vertexAttribPointer().
IfyouareusingWebGL2,youcanspecifytheindexyourselfinthevertexshadercode
andoverridethedefaultusedbythegraphicscard,e.g.
layout(location=3)invec4position;wouldsetthe
"position"attributetoindex3.
Integerattributes
WhiletheArrayBuffercanbefilledwithbothintegersandfloats,the
attributeswillalwaysbeconvertedtoafloatwhentheyaresenttothevertexshader.
Ifyouneedtouseintegersinyourvertexshadercode,youcaneithercastthefloat
backtoanintegerinthevertexshader(e.g.(int)floatNumber),oruse
gl.vertexAttribIPointer()fromWebGL2.
Defaultattributevalues
Thevertexshadercodemayincludeanumberofattributes,butwedon'tneedtospecify
thevaluesforeachattribute.Instead,wecansupplyadefaultvaluethatwillbe
identicalforallvertices.Wecancall
gl.disableVertexAttribArray()
totellWebGLtousethedefaultvalue,whilecalling
gl.enableVertexAttribArray()willreadthevaluesfromthearraybufferas
specifiedwithgl.vertexAttribPointer().
Similarly,ifourvertexshaderexpectse.g.a4-componentattributewith
vec4butinourgl.vertexAttribPointer()callwesetthe
sizeto2,thenWebGLwillsetthefirsttwocomponentsbased
onthearraybuffer,whilethethirdandfourthcomponentsaretakenfromthedefault
value.
Thedefaultvalueisvec4(0.0,0.0,0.0,1.0)bydefaultbutwecan
specifyadifferentdefaultvaluewith
gl.vertexAttrib[1234]f[v]().
Forexample,yourvertexshadermaybeusingapositionandacolorattribute.Most
mesheshavethecolorspecifiedataper-vertexlevel,butsomemeshesareofauniform
shade.Forthosemeshes,itisnotnecessarytoplacethesamecolorforeachvertex
intothearraybuffer,soyouusegl.vertexAttrib4fv()tosetaconstant
color.
Queryingcurrentsettings
Youcancallgl.getVertexAttrib()andgl.getVertexAttribOffset()togetthecurrentparametersforanattribute,e.g.the
datatypeorwhethertheattributeshouldbenormalized.KeepinmindthattheseWebGL
functionshaveaslowperformanceanditisbettertostorethestateinsideyour
JavaScriptapplication.However,thesefunctionsaregreatfordebuggingaWebGLcontext
withouttouchingtheapplicationcode.
Examples
Thisexampleshowshowtosendyourvertexattributestotheshaderprogram.Weusean
imaginarydatastructurewheretheattributesofeachvertexarestoredinterleavedwith
alengthof20bytespervertex:
position:WeneedtostoretheX,YandZcoordinates.Forhighest
precision,weuse32-bitfloats;intotalthisuses12bytes.
normalvector:WeneedtostoretheX,YandZcomponentsofthe
normalvector,butsinceprecisionisnotthatimportant,weuse8-bitsigned
integers.Forbetterperformance,wealignthedatato32bitsbyalsostoringa
fourthzero-valuedcomponent,bringingthetotalsizeto4bytes.Also,wetellWebGL
tonormalizethevaluesbecauseournormalsarealwaysinrange[-1,1].
texturecoordinate:WeneedtostoretheUandVcoordinates;for
this16-bitunsignedintegersofferenoughprecision,thetotalsizeis4bytes.We
alsotellWebGLtonormalizethevaluesto[0,1].
Forexample,thefollowingvertex:
{
"position":[1.0,2.0,1.5],
"normal":[1.0,0.0,0.0],
"texCoord":[0.5,0.25]
}
Willbestoredinthearraybufferasfollows:
Creatingthearraybuffer
First,wedynamicallycreatethearraybufferfromJSONdatausinga
DataView.NotetheuseoftruebecauseWebGLexpectsour
datatobeinlittle-endian.
//loadgeometrywithfetch()andResponse.json()
constresponse=awaitfetch('assets/geometry.json');
constvertices=awaitresponse.json();
//Createarraybuffer
constbuffer=newArrayBuffer(20*vertices.length);
//Fillarraybuffer
constdv=newDataView(buffer);
for(leti=0;i
延伸文章資訊
- 1WebGLRenderingContext.vertexAttribPointer() - Web APIs
The WebGLRenderingContext.vertexAttribPointer() method of the WebGL API binds the buffer currentl...
- 2webgl vertexAttribPointer步进和偏移函数 - 简书
如果每个顶点数据都创建一个缓冲对象,那么会导致创建很多缓冲对象,而且在编码的过程中会产生相同的代码.所以webgl 推出使用vertexAttribPointer()的步 ...
- 3What is the purpose of vertexAttribPointer? - Stack Overflow
it tells WebgL how to interpret the data: gl.vertexAttribPointer(attrib, index, gl.FLOAT, false, ...
- 4webGL: vertexAttribPointer 函数理解- SegmentFault 思否
void gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
- 5WebGLRenderingContext.vertexAttribPointer() - Web API 接口 ...
vertexAttribPointer() method of the WebGL API binds the buffer currently bound to gl.ARRAY_BUFFER...