GLSL Tutorial – Uniform Variables - Lighthouse3d.com
文章推薦指數: 80 %
GLSL Tutorial – Uniform Variables ... Uniform variables act as constants, at least for the duration of a draw call. The application feeds these variables to the ... About Tutorials VerySimple*Libs CGStuff Books Tutorials»GLSLTutorial-Core»GLSLTutorial–UniformVariables Addcomments Prev:AttributeVariables Next:UniformBlocks Uniformvariablesactasconstants,atleastforthedurationofadrawcall.Theapplicationfeedsthesevariablestothegraphicspipelineandtheyareaccessibleinallstagesofthepipeline,i.e.anyshadercanaccesseveryuniformvariable,aslongasitdeclaresthevariable.Thesevariablesarereadonly,asfarasshadersareconcerned. Uniformscanbegroupedinblocks,ordefinedindividually.Inherewewillstarttolookattheindividualdefinitions,andthenextsectionwilllookatuniformblocks. Insideashader,auniformisdefinedusingtheuniformkeyword.Forinstancetodefineavec4namedmyVarwecouldwriteinashader uniformvec4myVar; Uniformscanalsobeinitializedinsidetheshader,forinstancetoinitializeavec4wecouldproceedasfollows: uniformvec4myVar={0.5,0.2,0.7,1.0}; In-shader-initializationisgreatsinceitrelievesusfromhavingtosetuniforms.Wecansetadefaultvalueintheshaderinitialization,andonlyhavetosetavaluefromtheapplicationifwerequireadifferentvaluefortheuniformvariable. Insidetheapplication,tosetauniformvariable,wemustfirstgetitslocation,whichwecanretrievewiththefollowingfunction: [stextbox] GLintglGetUniformLocation(GLuintprogram,constchar*name); Params: program:thehandletothelinkedprogram name:thenameoftheuniformvariable Return:thelocationofthevariable,or-1ifthenamedoesnotcorrespondtoanactiveuniformvariable. [/stextbox] Anactiveuniformvariableisavariablethatitisactuallyusedinsidetheshader,notjustdeclared.Thecompilerisfreetothrowawayvariablesthatarenotusedinthecode.Therefore,evenifauniformisdeclaredintheshader,aslongasitisnotused,itsreportedlocationcanbe-1. Thereturnvalue,assumingthattheprogramislinkedandthatthevariableiseffectivelybeingusedinthecode,isthelocationofthevariable,whichlatercanbeusedtosetitsvalue(s).Inordertosetthevalues,OpenGLoffersalargefamilyoffunction,tocoverforalldatatypes,andseveralwaysofsettingthevalues.Forinstance,considerthevariablemyVarasdefinedabove.Tosetthevec4,andassumingpasanhandletoalinkedprogram,wecouldwrite: GLintmyLoc=glGetUniformLocation(p,"myVar"); glProgramUniform4f(p,myLoc,1.0f,2.0f,2.5f,2.7f); or,wecouldwrite floatmyFloats[4]={1.0f,2.0f,2.5f,2.7f}; GLintmyLoc=glGetUniformLocation(p,"myVar"); glProgramUniform4fv(p,myLoc,1,myFloats); Thesignatureofthesetwofunctionsisasfollows: [stextbox] voidglProgramUniform4f(GLuintprogram,GLintlocation,GLfloatf1,…,GLfloatf4); voidglProgramUniform4fv(GLuintprogram,GLintlocation,GLsizeicount,constGLfloat*values); Params: program:thehandletothelinkedprogram location:theuniform’slocationinprogramp f1…f4,values:thevaluestosettheuniform count:thenumberofitemstoset.Forbasicdatatypesthiswillalwaysbeone.Whenconsideringarrays,thenthisvaluerepresentsthenumberofelementsinthearraytobeset. [/stextbox] TherearesimilarfunctionsforallbasicdatatypesinGLSLandforthepredefinedmatrices. Arrays Considernowthatinourshaderwehaveanarraytypeofvariable,declaredasfollows: uniformvec4color[2]; Fromtheapplicationpointofview,wecanlookatthevariableasanarrayandsetallthecomponentsatonce.Thisistrueformostbasictypes,notstructs,seebelow. floatmyColors[8]={1.0f,0.0f,0.0f,0.0f,0.0f,1.0f,0.0f,0.0f}; GLintmyLoc=glGetUniformLocation(p,"color"); glProgramUniform4fv(p,myLoc,2,myColors); NoticethatwesetthethirdparameterofglProgramUniform4fvto2,sincewearesettingtwoelementsofthearray,i.e.twovec4.TheapplicationarraymyColorshaseightfloatsasrequired. Anotherapproachwouldbetoseteachelementindividually.Forinstance,assumethatweonlywanttosetthesecondelementoftheGLSLarray,i.e.color[1].Thenwecanwrite: GLfloataColor[4]={0.0f,1.0f,1.0f,0.0f}; myLoc=glGetUniformLocation(p,"color[1]"); glProgramUniform4fv(p,myLoc,1,aColor); ThereisaglProgramUniformfunctionforeachbasicdatatypeandtheycomeupintwoflavoursasshownforthevec4case: [stextbox] voidglProgramUniform4f(GLuintprogram,GLintlocation,GLfloatv1,…,GLfloatv4); voidglProgramUniform4fv(GLuintprogram,GLintlocation,GLsizeicount,GLfloat*v); Params: program:thelinkedprogramhandle location:thelocationofthevariable v1..v4:thevaluesforeachcomponentofthevec4 count:thenumberofvec4toset v:apointertowherethefloatdatamaybefound [/stextbox] Formatrices,thereisaspecialversionofthisfunction,seebelowtheexampleforamat4: [stextbox] voidglProgramUniformMatrix4fv(GLuintprogram,GLintlocation,GLsizeicount,GLbooleantranspose,GLfloat*v); Params: program:thelinkedprogramhandle location:thelocationofthevariable count:thenumberofvec4toset transpose:iftruethematrixwillbetransposedpriortoloadingtotheuniform v:apointertowherethefloatdatamaybefound [/stextbox] Structs InGLSLwecandefinestructs,inawaysimilartoC.Forinstance,thefollowingsnippetofcodedeclaresastructwithtwovec4s,anddefinesauniformvariableofthattype. structColors{ vec4Color1; vec4Color2; }; uniformColorsmyColors; Tousethestruct’sfieldsinsideashaderweusethesamenotationasinC.Forinstance,thefollowingmainfunctionassumesthedeclarationsabove: voidmain() { vec4aColor=myColors.Color1+myColors.Color2; ... } TosetthesevariablesintheapplicationwealsousethesamenotationasinC.Wecan’tsetthestructasawhole,asitcan’tgetalocationforit.Wemustsetitfieldbyfield.Thefollowingexampleshowshow: floatmyFloats[8]={0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0}; GLintmyLoc=glGetUniformLocation(p,"myColors.Color1"); glProgramUniform4fv(p,myLoc,1,myFloats); myLoc=glGetUniformLocation(p,"myColors.Color2"); glProgramUniform4fv(p,myLoc,1,&(myFloats[4])); Workingwitharraysofstructsissimple.Considerthefollowinguniformdeclaration: uniformColorsmyColors[2]; Intheshaderwecanwritethefollowing: voidmain() { vec4aColor=myColors[0].Color1+myColors[1].Color2; ... } Insideourapplicationweproceedinthesamemanner: GLintmyLoc; floatmyFloats[8]={0.0,1.0,0.0,0.0,1.0,0.0,0.0,0.0}; floatmyOtherFloats[8[={1.0,1.0,0.0,0.0,0.0,1.0,1.0,0.0}; myLoc=glGetUniformLocation(p,"myColors[0].Color1"); glProgramUniform4fv(p,myLoc,1,myFloats); myLoc=glGetUniformLocation(p,"myColors[0].Color2"); glProgramUniform4fv(p,myLoc,1,&(myFloats[4])); myLoc=glGetUniformLocation(p,"myColors[1].Color1"); glProgramUniform4fv(p,myLoc,1,myOtherFloats); myLoc=glGetUniformLocation(p,"myColors[1].Color2"); glProgramUniform4fv(p,myLoc,1,&(myOtherFloats[4])); Likethis:LikeLoading... Prev:AttributeVariables Next:UniformBlocks 4Responsesto“GLSLTutorial–UniformVariables” Larrysays: 29/05/2014at4:34PM Nicearticle–thanks Suggestedtypofix: “…itreliefsusfromhavingtosetuniforms.” shouldbe “…itrelievesusfromhavingtosetuniforms.” Reply ARFsays: 03/06/2014at12:16PM Fixed,Thanks! Reply MingJinsays: 20/06/2013at2:58PM voidglGetProgramUniform4f(GLuintprogram,GLintlocation,GLfloatv1,…,GLfloatv4); Ithinkthefunctionshouldinsteadbe“glProgramUniform4f”? Reply ARFsays: 23/06/2013at2:18PM Fixed.Thanks. Reply LeaveaReply Cancelreply ThissiteusesAkismettoreducespam.Learnhowyourcommentdataisprocessed. GoogleAds TagCloudanamorphosis animation anti-aliasing Assimp Blender C Courses cpu debug DevIL drawings fractals FreeGLUT games GLSL GLUT google GPU JSON Kinect maths Maya models Ogre OpenCL OpenGL OpenGLES Optix physics pipeline Pixar profiler programming real-time shaders Specs textures tutorials VRML VS*L VSFL VSML VSPL VSShaderLib WebGL Categories Apps&Demos(15) Art(12) Books(15) CGTechniques(6) Docs(7) GameEngine(2) Games(6) Misc(11) Models&Textures(19) Movies(23) Physics(2) Programming(80) Textures(7) Tools(26) Tutorials(63) Uncategorized(18) PopularPosts NewSite 36views|0comments GLSLCoreTutorial 25views|0comments Notepad++GLSL4.3SyntaxHighlight 24views|0comments WebGL–ImportingaJSONformatted3DModel 21views|0comments NoiseforGLSL 16views|0comments WebGL–Converting3DmodelstoJSONformattedfiles 12views|0comments WebGL–BasicMaterialListfromTeapots.c 11views|0comments TheHistoryoftheTeapot 8views|0comments OpenGL3.3Pipeline 8views|0comments ShaderXBookSeries 8views|0comments Links AMDDeveloperCentral Codeflow Flipcode G-TrucCreation GameDev.net Geeks3D HugoElias'Site Humus3D IñigoQuílezSite KhronosGroup Nehe nVidiaDeveloper OpenGL.org PaulBourke'sSite Real-TimeRendering Search Learning Tutorials GLSLTutorial Pipeline VertexShader PrimitiveAssembly Tessellation GeometryShader GSExamples RasterizationandInterpolation FragmentShader OpenGLSetup CreatingaShader CreatingaProgram SetupExample Troubleshooting:theInfolog CleaningUp DataTypes StatementsandFunctions Subroutines Comm.App=>Shader AttributeVariables UniformVariables UniformBlocks Intershadercomm. SpacesandMatrices InterpolationIssues OpenGLskeleton HelloWorld ColorExample Lighting DirLightsperVertexI DirLightsperVertexII DirLightsperPixel PointLights Spotlights TextureCoordinates TexturingwithImages Index VerySimple*Libs CGStuff GoogleAds GoogleAds ThissiteusescookiestopersonaliseadsbyGoogleinordertokeepitfreeAcceptSeethispageonhowGoogleusestheinformationaboutyourusageofthissitePrivacy&CookiesPolicy Close PrivacyOverview Thiswebsiteusescookiestoimproveyourexperiencewhileyounavigatethroughthewebsite.Outofthese,thecookiesthatarecategorizedasnecessaryarestoredonyourbrowserastheyareessentialfortheworkingofbasicfunctionalitiesofthewebsite.Wealsousethird-partycookiesthathelpusanalyzeandunderstandhowyouusethiswebsite.Thesecookieswillbestoredinyourbrowseronlywithyourconsent.Youalsohavetheoptiontoopt-outofthesecookies.Butoptingoutofsomeofthesecookiesmayaffectyourbrowsingexperience. Necessary Necessary AlwaysEnabled Necessarycookiesareabsolutelyessentialforthewebsitetofunctionproperly.Thiscategoryonlyincludescookiesthatensuresbasicfunctionalitiesandsecurityfeaturesofthewebsite.Thesecookiesdonotstoreanypersonalinformation. Non-necessary Non-necessary Anycookiesthatmaynotbeparticularlynecessaryforthewebsitetofunctionandisusedspecificallytocollectuserpersonaldataviaanalytics,ads,otherembeddedcontentsaretermedasnon-necessarycookies.Itismandatorytoprocureuserconsentpriortorunningthesecookiesonyourwebsite. %dbloggerslikethis:
延伸文章資訊
- 1高级GLSL
Uniform块布局
- 2一起幫忙解決難題,拯救IT 人的一天
GLSL(OpenGL Shading Language Language)是OpenGL 的Shader 語言,它長得有點像C語言, ... uniform type uniform_name...
- 3Uniform (GLSL) - OpenGL Wiki - Khronos Group
Uniform (GLSL) ... Shader stages: ... A uniform is a global Shader variable declared with the "un...
- 4Advanced GLSL - LearnOpenGL
OpenGL gives us a tool called uniform buffer objects that allow us to declare a set of global uni...
- 5OpenGL基础- 统一变量Uniform - 知乎专栏
OpenGL基础: Uniform变量-- 即统一变量简单理解就是一个GLSL shader中的全局常量,可以随意在任意shader(vertex shader, geometry shader...