What exactly is gl_VertexID? - Graphics and GPU Programming

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

For this, I was expecting that gl_VertexID would be the index into the vertex buffer of the current vertex. My initial testing didn't work, so I ... AllContent Blogs Forums News Tutorials LogIn SignUp  Login Username/Email Password Rememberme Forgotpassword? Login or Don'thaveaGameDev.netaccount?Signup  Forgotyourpassword? EmailAddress ResetPassword Pleasecontactusifyouhaveanytroubleresettingyourpassword. Home Blogs Careers Careers Forums News Portfolios Projects Tutorials New?Learnaboutgamedevelopment FollowUs ChatintheGameDev.netDiscord! BacktoGraphicsandGPUProgramming Whatexactlyisgl_VertexID? GraphicsandGPUProgramming Programming Startedby willvarfar June28,201110:42AM 7 comments,lastbyHodgman10 years,10 monthsago Advertisement willvarfar Author 102 June28,201110:42AM Ihaveaverysimpleheight-map-basedmeshoftriangles. ThebackstoryisthatIwanttomakeapoor-man'sdisplacementmappingusingasinglevertexarrayofbyteheightswithoutxzandusingmodulararithmeticonthegl_VertexIDtodeterminethepositiononthe2Dgridofthevertex.Forthis,Iwasexpectingthatgl_VertexIDwouldbetheindexintothevertexbufferofthecurrentvertex.Myinitialtestingdidn'twork,soItriedtomakeadebugversiontounderstandexactlywhatvaluesgl_VertexIDhas. SoIhaveanormalvertexarraythatisproperxyzpoints: #workoutthescalingforourworldcoordinates max_height=0.4/255. tx_scale_x,tx_scale_y=1./w,1./h px_scale_x,px_scale_y=2./w,2./h #makethetiles image=image.load()#getatthepixels vertices=numpy.empty((w*h,3),dtype=numpy.float32) tx_coords=numpy.empty((w*h,2),dtype=numpy.float32) printself,"generating",len(vertices),"vertices" foryinxrange(h): forxinxrange(w): height=image[x,y] vertices[y*w+x]=(1.-x*px_scale_x,height*max_height,1.-y*px_scale_y)#Yisupwardsin3D tx_coords[y*w+x]=(x*tx_scale_x,1.-y*tx_scale_y) #uploadverticesintoVBOetc... AndIamdrawingitinasingleglDrawElementscallusingaboundGL_ELEMENT_ARRAY_BUFFER_ARBindexarray. Andtodebugthis,Isimplymadeavertexshaderthat'llcolourthefirst1000verticesredandtherestgray. if(gl_VertexID<1000){ test_colour=vec3(1.0,0,0); }else{ test_colour=vec3(0.8,0.8,0.8); } AsmyverticesareinmyVBOinscanlines,andIwasexpectinggl_VertexIDtobetheindexofthevertexinthisVBO,Iwasexpectingthethe0gl_VertexIDtocorrespondtothetop-leftvertexandsoonregardlessoftheorderandnumberoftrianglesIcreatewiththem. Iexpectedthefirstfewrowstoberedandtherestgray;however,Iamgettingaspeckledpatterninstead.Alsonotethesharpedgesontwosidesofeachchevron-I'dhaveexpectedittocolourequallyonallfacessharingthevertex. Cancel Save Danny02 279 June28,201112:28PM Checkyourindexcreationagain,thereshouldbeanerror,becauseformeeverythingworksfinewhenIuseagridlikeuwithexactlyyourcodesnipped. Cancel Save willvarfar Author 102 June28,201103:12PM Checkyourindexcreationagain,thereshouldbeanerror,becauseformeeverythingworksfinewhenIuseagridlikeuwithexactlyyourcodesnipped. IupdatedmyquestiontoillustratehowIcreatemyvertexarray. ThinkthisisjustabugintheInteldriversonmylaptopperhaps? Cancel Save Danny02 279 June28,201104:19PM coulduposthowucreateyourindexbuffer? alsowhywoulduuseaarrayofheights(possibleuploadedasanuniform?)andindexinitwiththeindex,justaddanheightattributetoyourverticeswhichucanupdateseparablytoyourotherattributes(i.e.position) Cancel Save Trienco 2,555 June28,201105:11PM coulduposthowucreateyourindexbuffer? alsowhywoulduuseaarrayofheights(possibleuploadedasanuniform?)andindexinitwiththeindex,justaddanheightattributetoyourverticeswhichucanupdateseparablytoyourotherattributes(i.e.position) Ordon'thaveanydatabesidesheight,becausex/zforanychunkcanbecalculatedfromtheindexandthechunkoffsetsetasauniform.Texturecoordinatescanalsobecalculatedontheflyandnormalsmightcomefromanormalmap.Whichisbasicallywhathewantstodotosavealotofmemory. IfthevertexindexwouldhavebeenavailableintheshaderyearsagoIwouldn'thavehadtouseasillysmallVBOwithx/zcoordinates(reusedforeverysinglechunk). Sinceyoushouldknowthelargestindex,whatdoesitlooklikeifyousetgl_VertexID/maxIndexascolor?Maybethatgivesyouabetterideaoftheactualvalues. Cancel Save f@dzhttp://festini.device-zero.de willvarfar Author 102 June28,201106:45PM Ordon'thaveanydatabesidesheight,becausex/zforanychunkcanbecalculatedfromtheindexandthechunkoffsetsetasauniform.Texturecoordinatescanalsobecalculatedontheflyandnormalsmightcomefromanormalmap.Whichisbasicallywhathewantstodotosavealotofmemory. Exactlymyplan!Further,Iwanttoreusemyindex-arrayusingglDrawRangeElementsBaseVertexsoIonlyneedanindexarrayforeachgeo-mipmapandlevel...AndthenIfillupallthatmemoryIsavewithotherstuff However,myattemptsatinferring2Dpositionfromgl_VertexIDusingmod()anddivides(&and>>arenotsupportedbymycard)isfailingbadlybecausethevaluesofgl_VertexIDthatIencountermakenosense.Imusthavemadeanelementarymistake? Hereistheabsoluteminimumusefultestcase(pyopengl/pygame,butoughttobeeasilyrewrittenin,say,c)-appreciateifpeoplerunittooandseeiftheircardsgiveequivresults: importos,numpy,array,sys fromOpenGL.GLimport* fromOpenGL.GLimportshaders fromOpenGL.GLUimport* fromOpenGL.GLUTimport* fromOpenGL.arraysimportArrayDatatypeasADT importpygame frompygame.localsimport* w=h=100 #createawindow pygame.display.set_mode((800,600),HWACCEL|OPENGL|DOUBLEBUF) glutInit() glViewport(0,0,800,600) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(60.,float(w)/h,.1,1000.) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt(0,1,-2,0,0,0,0,1,0) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) glEnable(GL_CULL_FACE) glClearColor(1.,1.,1.,0.) #createthevertexarray vertices=numpy.empty((w*h,3),dtype=numpy.float32) foryinxrange(h): forxinxrange(w): vertices[y*w+x]=(1.-x*2./w,0,1.-y*2./h) vbo=glGenBuffers(1) glBindBuffer(GL_ARRAY_BUFFER,vbo) glBufferData(GL_ARRAY_BUFFER,ADT.arrayByteCount(vertices),ADT.voidDataPointer(vertices),GL_STATIC_DRAW) vertices=vbo glEnableClientState(GL_VERTEX_ARRAY) glVertexPointer(3,GL_FLOAT,0,None) #createtheindexarray num_triangles=(w-1)*(h-1)*2 indices=numpy.empty((num_triangles,3),dtype=numpy.uint32) tri=0 foryinxrange(h-1): forxinxrange(w-1): quad=y*w+x indices[tri]=(quad,quad+w,quad+w+1);tri+=1 indices[tri]=(quad+w+1,quad+1,quad);tri+=1 vbo=glGenBuffers(1) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,vbo) glBufferData(GL_ELEMENT_ARRAY_BUFFER,ADT.arrayByteCount(indices),ADT.voidDataPointer(indices),GL_STATIC_DRAW) indices=vbo #createtheshaders vertex_shader=shaders.compileShader(""" varyingvec4test_colour; voidmain(){ if(gl_VertexID<50){//evenwith==0 test_colour=vec4(1.0,0,0,1); }else{ test_colour=vec4(0.8,0.8,0.8,1); } gl_Position=gl_ModelViewProjectionMatrix*gl_Vertex; }""",GL_VERTEX_SHADER) fragment_shader=shaders.compileShader(""" varyingvec4test_colour; voidmain(){ gl_FragColor=test_colour; }""",GL_FRAGMENT_SHADER) glUseProgram(shaders.compileProgram(vertex_shader,fragment_shader)) #drawthescene glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glDrawElements(GL_TRIANGLES,num_triangles*3,GL_UNSIGNED_INT,None) pygame.display.flip() #waitforESC whileTrue: event=pygame.event.poll() if(event.type==KEYDOWN)and(event.key==K_ESCAPE): break Cancel Save willvarfar Author 102 July01,201106:05AM IambeginningtosuspectmyintegratedInteldrivers,whichhavenotbeenparticularlycompliant Anybodyabletoconfirmthat,inaperfectdriver,whendrawnwithanelementsarray,thegl_VertexIDistheindexintotheVBOcontainingthevertices? Cancel Save V-man 813 July01,201102:51PM Inteldriversarealwaysbuggy.Therehavebeenthousandsofpostaboutitovertheyears.Stopwastingyourtimewithit. Cancel Save Sig:http://glhlib.sourceforge.net anopensourceGLUreplacementlibrary.MuchmoremodernthanGLU. floatmatrix[16],inverse_matrix[16]; glhLoadIdentityf2(matrix); glhTranslatef2(matrix,0.0,0.0,5.0); glhRotateAboutXf2(matrix,angleInRadians); glhScalef2(matrix,1.0,1.0,-1.0); glhQuickInvertMatrixf2(matrix,inverse_matrix); glUniformMatrix4fv(uniformLocation1,1,FALSE,matrix); glUniformMatrix4fv(uniformLocation2,1,FALSE,inverse_matrix); Hodgman 52,712 July01,201103:19PM Inteldriversarealwaysbuggy.Therehavebeenthousandsofpostaboutitovertheyears.Stopwastingyourtimewithit.Mayaswellbesaying"JustuseD3D"... Cancel Save .22RacingSeries. Share: Thistopicisclosedtonewreplies. Advertisement Advertisement PopularTopics ShouldIevenbotherdoingmarketingduringthesetimes? GamesBusinessandLaw Wheredoyoustartwhencreatingagame? WritingforGames buildinggamewithdifferentprogrammers GeneralandGameplayProgramming Jobsforpsychologyingames? GamesCareerDevelopment Gravitationalaccelerationcalculation MathandPhysics Bestwaytovalidatealgorithms? ForBeginners Reticulatingsplines AboutGameDev.net TermsofService PrivacyPolicy ContactUs Copyright(c)1999-2021GameDev.net,LLC BacktoTop



請為這篇文章評分?