Uniform (GLSL) - OpenGL Wiki - Khronos Group

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

Uniform (GLSL) ... Shader stages: ... A uniform is a global Shader variable declared with the "uniform" storage qualifier. These act as parameters ... Uniform(GLSL) FromOpenGLWiki Jumptonavigation Jumptosearch GLSL OpenGLShadingLanguage Shader Objects Compilation Introspection Thecorelanguage Variabletypes Typequalifiers Layoutqualifiers Uniformvariables Samplervariables Imagevariables Built-invariables Interfaceblocks Uniformblocks Shaderstorageblocks SPIR-V Shaderstages: VertexShader Tessellation GeometryShader FragmentShader ComputeShader Othershadinglanguages AuniformisaglobalShadervariabledeclaredwiththe"uniform"storagequalifier.Theseactasparametersthattheuserofashaderprogramcanpasstothatprogram.Theirvaluesarestoredinaprogramobject. Uniformsaresonamedbecausetheydonotchangefromoneshaderinvocationtothenextwithinaparticularrenderingcallthustheirvalueisuniformamongallinvocations.Thismakesthemunlikeshaderstageinputsandoutputs,whichareoftendifferentforeachinvocationofashaderstage. Contents 1GLSLdefinitionandbehavior 1.1Explicituniformlocation 2Activeuniforms 3Implementationlimits 4Uniformmanagement 4.1Changinguniformvalues 5Uniformblocksandbuffers 6Accessinguniforminformation GLSLdefinitionandbehavior UniformvariablesmustbedefinedinGLSLatglobalscope. Uniformscanbeofanytype,oranyaggregationoftypes.ThefollowingarealllegalGLSLcode: structTheStruct { vec3first; vec4second; mat4x3third; }; uniformvec3oneUniform; uniformTheStructaUniformOfArrayType; uniformmat4matrixArrayUniform[25]; uniformTheStructuniformArrayOfStructs[10]; Uniformsareimplicitlyconstant,withintheshader(thoughtheyarenotConstantExpressions).Attemptingtochangethemwithshadercodewillresultinacompilererror.Similarly,youcannotpassauniformasanoutorinoutparametertoafunction. UniformsareintendedtobesetbytheuserfromOpenGL,ratherthanwithintheshader.However,youcaninitializethemtoadefaultvalueusingstandardGLSLinitalizersyntax: uniformvec3initialUniform=vec3(1.0,0.0,0.0); Thiswillcausetheuniformtohavethisvectorasitsvalue,untiltheuserchangesit. PlatformIssue(Unknown):Somedriversdonotimplementuniforminitializerscorrectly. Explicituniformlocation ExplicitUniformLocation Coreinversion 4.6 Coresinceversion 4.3 CoreARBextension ARB_explicit_uniform_location V·E UniformsdefinedoutsideofInterfaceBlockshavealocation.Thislocationcanbedirectlyassignedintheshader,usingthissyntax: layout(location=2)uniformmat4modelToWorldMatrix; CallingglGetUniformLocation(prog,"modelToWorldMatrix")isguaranteedtoreturn2.Itisillegaltoassignthesameuniformlocationtotwouniformsinthesameshaderorthesameprogram.Evenifthosetwouniformshavethesamenameandtype,andaredefinedindifferentshaderstages,itisnotlegaltoexplicitlyassignthemthesameuniformlocation;alinkererrorwilloccur. Allnon-array/structtypeswillbeassignedasinglelocation.Arraysandstructswillbeassignedsequentiallyincreasinglocations,startingwiththegivenlocation.Giventhis: layout(location=2)uniformmat4some_mats[10]; some_matswillbeassignedalloftheuniformlocationsonthehalf-openrange[2,12).Thiswillapplyfornestedtypes.Considerthefollowing: structThingy { vec4an_array[3]; intfoo; }; layout(location=2)uniformThingysome_thingies[6]; EachThingytakesup4uniformlocations;thefirstthreegoingtoan_arrayandthefourthgoingtofoo.Thus,some_thingiestakesup24uniformlocations. UploadingarraysofuniformswithoneoftheglUniform*vfunctionswillwork.Forexample,uniformlocation2representsthearray`some_thingies[0].an_array`.Assuch,youcanuploadanarrayofvec4stothisarraywithglUniform4fv(2,3,...);. Iftwouniformsinaprogramaregiventhesameexplicitlocation,thentheyrefertothesameuniform.Thismeanstheymustalsomatchinvariablename,type,array-index,qualifiers,etc.Thefollowingwouldbeillegal: layout(location=2)uniformmat4some_mats[10]; layout(location=6)uniformvec4some_vecs[4]; some_matstakesup10uniformlocations,from[2,12).Butsincesome_vecsstartsatuniformlocation6,itwouldhavethesamelocationassome_mats[4].Butitwouldn'thavethesamename,orsametype,orothercharacteristics.Evenifsome_vecswasamat4,itwouldnotbethesame,sincetheydon'thavethesamenameorsamearrayindex. ThemaximumnumberofavailablelocationswithinasingleprogramisGL_MAX_UNIFORM_LOCATIONS,whichwillbeatleast1024locations.Youmaynotuseauniformlocationoutsideoftherange[0,GL_MAX_UNIFORM_LOCATIONS),normaythesequentialassignmentofuniformlocationsduetoarray/structaggregationgooutsideofthisrange. Activeuniforms GLSLcompilersandlinkerstrytobeasefficientaspossible.Therefore,theydotheirbesttoeliminatecodethatdoesnotaffectthestageoutputs.Becauseofthis,auniformdefinedinashaderfiledoesnothavetobemadeavailableinthelinkedprogram.Itisonlyavailableifthatuniformisusedbycodethataffectsthestageoutput,andthattheuniformitselfcanchangetheoutputofthestage. Therefore,auniformthatisexposedbyafullylinkedprogramiscalledan"active"uniform;anyotheruniformspecifiedbytheoriginalshadersisinactive.Inactiveuniformscannotbeusedtodoanythinginaprogram. Implementationlimits Thenumberofactiveuniformsavailableisboundbyasetoflimits.Eachshaderstagehasalimitonthenumberofavailableuniforms.Theper-stagelimitsaretheconstantsGL_MAX_VERTEX_UNIFORM_COMPONENTS,GL_MAX_GEOMETRY_UNIFORM_COMPONENTS,andGL_MAX_FRAGMENT_UNIFORM_COMPONENTS(alsoGL_MAX_TESS_CONTROL_UNIFORM_COMPONENTSandGL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTSifOpenGL4.0orARB_tessellation_shader,andGL_MAX_COMPUTE_UNIFORM_COMPONENTSifOpenGL4.3orARB_compute_shader).YoucanquerytheselimitswithglGetIntegerv,buttheyareallquitegenerous—atleast1024inOpenGL3.0+. Thelimitreferstothequantityofspaceforindividualfloats,integers,orbooleans.Avec3isexpectedtotakeup3components.Matrixtypeswilltakeupnomorethan4*thesmallestcountofrows/columns.Thus,amat2x3willnottakeupanymorethan8componentsandmaytakeupless.Arraysofthesewilltakeupthearraysize*thatnumberofcomponents.Double-precisionvalues(fromGL4.0/ARB_gpu_shader_fp64)willtakeup2xthespaceofsingle-precisionequivalents. Implementationnote:OpenGLimplementationsareallowedtorejectshadersforimplementation-dependentreasons.Soyoucanhavefeweractiveuniformcomponentsbyyourreckoningandstillfailtolinkduetouniformlimits.Thisisusuallyonhardwarethatisinnatelyvectorhardware.Pre-GeForce8xxxhardware,andallATihardwaredoesthis.Inthiscase,youshouldassumethateachseparateuniformtakesup4components,muchlikeitwouldinD3D.Thatmeansa"uniformfloat"is4components,amat2x4is16components(eachrowis4components),butamat4x2is8components. Dorecallthattheselimitsareforactiveuniformsonly.Uniformsthataredeemedinactivearenotrelevanttothislimit. ThemaximumnumberofuniformlocationsthatcanbeexplicitlyassignedinaprogramisdefinedbyGL_MAX_UNIFORM_LOCATIONS.Thislimitsthenumbersyoucanusewhengivinguniformsexplicitlocations. Uniformmanagement LikeregularOpenGLObjects,programobjectsencapsulatecertainstate.Inthiscase,thisstateisasetofuniformsthatwillbeusedwhenrenderingwiththatprogram.Allofthestageswithinaprogramobjectusethesamesetofuniforms.Thus,ifyouhaveauniformnamed"projectionMatrix"definedasamat4inboththevertexandthefragmentstages,thentherewillbeonlyoneuniformofthatnameexposedbytheprogramobject.Changingthisuniformwillaffectboththevertexandfragmentstages. Therefore,itisaprogramlinkererrortohaveauniforminavertexandfragmentshaderthatusesthesamename,buthasadifferenttypeineachshader. Eachactiveuniformhasalocation.Thelocationisanumerichandletothatuniform;itfunctionsasashorthandthatisfastertosearchforthantheuniform'sname.Uniformlocationsareuniquetoaspecificprogram.Ifyoudonotexplicitlyassignauniformtoalocation(viatheOpenGL4.3orARB_explicit_uniform_locationfeaturementionedabove),thenOpenGLwillassignthemarbitrarily.Inthiscase,evenifyoudefinetheexactsamesetofuniformsintwodifferentprograms,OpenGLdoesnotguaranteethatthesameuniformsinthetwoprogramswillhavethesamelocation.Soifyoudonotexplicitlydefinethelocationsforuniforms,youmustkeeptrackofthemindividuallyforeachprogram. Ifyouhaveauniformname,youcangettheuniformlocationviaProgramIntrospection.Thenamingconventionforvariablesallowsyoutogettheuniformlocationofanarray(ofbasictypes)asawhole,aswellaselementswithinthearrayortheelementsofstructures. ForarraysofBasicTypes,thelocationofeachelementinthearraywillbethelocationofthearray+thearrayindex.However,forstructs(orarraysofstructs),ifthelocationswerenotexplicitlyspecifiedthenthelocationofanyparticularelementwillhavenorelationtoanyotherelement.Soyoucannotcountonthenextelementbeingonelocationindexhigherthantheprevious.Thisistrueevenforarraysofstructs. Changinguniformvalues Thepurposeofgettingtheuniformlocationistochangetheuniform'svalue.ThisisdonewithalargesetoffunctionsoftheformglUniform*,where*definesthetypeofvaluetoupload.Thesecanuploadmatrices,vectors,individualvalues,andarraysofeachofthese. However,inordertochangeauniformvalue,youmustfirstbindtheprogramtothecontextwithglUseProgram.TheglUniform*functionsdonottakeaprogramobjectname;theyusethecurrentlyboundprogram.IfyouareusingOpenGL4.1orARB_separate_shader_objects,youmayusetheglProgramUniform*functionstosetuniformsdirectlyonaprogram,withouthavingtobindtheprogramfirst. Uniformblocksandbuffers Mainarticle:UniformBufferObjects Itisoftenusefultostoreasetofuniformsinstoragethatisseparatefromtheprogramobject.Thiscanallowforfastswitchingbetweensetsofuniforms,aswellashavingmultipleprogramsshareuniformdata.ThisisdonebydeclaringagroupofuniformstobeinanInterfaceBlock,thenusingstorageinaBufferObjecttostorethoseuniforms.Collectively,thisconceptiscalledUniformBufferObjects. Opaquetypeslikesamplerscannotbepartofuniformblocks. Accessinguniforminformation Mainarticle:ProgramIntrospection Informationaboutuniforms,whetherglobalorwithininterfaceblocks,canbequeriedviatheintrospectionAPI. Retrievedfrom"http://www.khronos.org/opengl/wiki_opengl/index.php?title=Uniform_(GLSL)&oldid=14664" Categories:PagesusingdeprecatedsourcetagsOpenGLShadingLanguage Navigationmenu Personaltools CreateaccountLogin Namespaces PageDiscussion Variants Views ReadViewsourceViewhistory More Search Navigation MainPageGettingStartedDownloadOpenGLRegistryReferencePagesReferenceGuideNewsCommunityForumsAboutOpenGL Help ContactUsPrivacyPolicyHelpEditingRecentchanges Tools WhatlinkshereRelatedchangesSpecialpagesPrintableversionPermanentlinkPageinformationCitethispage



請為這篇文章評分?