Core Language (GLSL) - OpenGL Wiki - Khronos Group

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

GLSL uses the standard C/C++ set of statements. It has selection statements (if-else and switch-case), iteration statements (for, while, and ... CoreLanguage(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 TheOpenGLShadingLanguageisaC-stylelanguage,soitcoversmostofthefeaturesyouwouldexpectwithsuchalanguage.Controlstructures(for-loops,if-elsestatements,etc)existinGLSL,includingtheswitchstatement.Thissectionwillnotcovertheentirelanguageindetail;theGLSLspecificationcanhandlethat.ThisWikipagewillnotethedifferencesbetweenGLSLandC. Contents 1Compilationsettings 1.1Version 1.1.1OpenGLandGLSLversions 1.1.2Extensions 2Preprocessordirectives 2.1#linedirective 2.2Standardmacros 3Reservednames 4Types 5Qualifiers 6Expressions 6.1Constantexpression 6.1.1Integralconstantexpression 6.2Dynamicallyuniformexpression 6.2.1Invocationgroup 6.2.2Uses 6.2.3Examples 7Functions 7.1Recursion 7.2Parameters 8Controlflow Compilationsettings TheOpenGLShadingLanguagerequirescertaininformationtobepresentedearlyinashaderobject'scompilation.Inacommand-line-basedcompiler,thesewouldbecommand-linecompileroptions.GLSL'scompilationmodelinsteadrequiresthemtobepartofthelanguage. Theseshouldbeinthefirstlinesofthefirststringassociatedwithashaderobject.Ifyouwanttogloballyapplythese,thenyoushouldputtheminastringthatisfirstinthearrayofstringspassedtotheshaderobjectwithglShaderSource,ortoglCreateShaderProgram. Version TheOpenGLShadingLanguagehasgonethroughanumberofrevisions,someofthemquitesubstantial.AspartoftheOpenGLSpecification,eachversionofOpenGLisrequiredtosupportspecificversionsofGLSL;itmayoptionallysupportmore. TospecifywhichversionofGLSLshouldbeusedtocompile/linkashader,usethisdirective: #version150 Thiswouldtellthecompilertocompileforversion1.50,orerrorifthatversionisnotavailable. Theversionnumbercanbefollowedbytheprofilename.Thiscanbecoreorcompatibility.Ifaprofilenameisnotspecified,thedefaultiscore. The#versiondirectivemustappearbeforeanythingelseinashader,saveforwhitespaceandcomments.Ifa#versiondirectivedoesnotappearatthetop,thenitassumes1.10,whichisalmostcertainlynotwhatyouwant. OpenGLandGLSLversions EveryOpenGLversionsince2.0hasbeenreleasedwithacorrespondingGLSLversion.However,theGLSLversionnumberswerenotalwaysinsyncwiththeGLversion.Hereisatable: OpenGLVersion GLSLVersion 2.0 1.10 2.1 1.20 3.0 1.30 3.1 1.40 3.2 1.50 ForallversionsofOpenGL3.3andabove,thecorrespondingGLSLversionmatchestheOpenGLversion.SoGL4.1usesGLSL4.10. Extensions ManyOpenGLExtensionsmodifyGLSL'sbehaviorandfunctionalityaswell.UnlikeregularOpenGL,whereextensionsareimplicitlyalwaystherewhetheryouuseitornot,GLSLextensionsmustexplicitlybespecifiedintheparticularshaderstringbeingcompiled. Similartothe#versiondirective,theusercanactivatespecificextensionswiththe"#extension"directive.Youshouldputthesedefinitionsbeforeanyotherlanguagefeatures,butaftertheversiondeclaration.Thesyntaxisasfollows: #extensionextension_name​ :behavior​ Theextension_name​canalsobethestringall.Thismeansitworksforallextensions.Theavailablebehaviorsare: enable:Causesthenamedextensiontowork;iftheimplementationdoesnotsupporttheextension,itonlygivesawarning.Failsifusedwithall. require:Causesthenamedextensiontowork;iftheimplementationdoesnotsupporttheextension,itfails.Italsofailsifusedwithall. warn:Causesthenamedextensiontowork;however,usingtheextensionwillemitwarnings.Ifusedwithall,thentheuseofanyextensionswillemitwarnings. disable:Preventsthenamedextensionfromworkingatall.Thus,anyuseofitwillbeseenasundefinedsyntaxandcauseanerror.Ifusedwithall,thenthispreventsanyextensionsfromworking. Preprocessordirectives Allofthekeywordsbeginningwith#arepreprocessordirectives,muchlikewithC,although#lineisdifferent.GLSLprovidesmostofthestandardCsetofpreprocessordirectives(#define,#if,etc),inadditiontotheoneslistedabove.Themostnotableomissionis#include. Macroexpansiondoesnotworkon#versionand#extensiondirectives. #linedirective The#linedirectiveallowsyoutochangethecurrent__FILE__and__LINE__values,andisdifferentfromC.Ithastheforms: #lineline #linelinesource-string-number Thelineafterthe#linedirectiveinthesourcewillbesettothegivenlinenumber.Forexample,ifyouhave"#line4"ononelineand"error"onthenext,then"error"willbeonline4ifitisanerror.The#linedirectivedoesnotsupportsourcefilesasinC. Standardmacros GLSLdefinesanumberofmacros.__FILE__isnotafilename;itisadecimalintegerrepresentingwhichstringinthelistofstringsgiventotheshader.__LINE__isthelinenumber.__VERSION__isadecimalintegerrepresentingtheGLSLversionbeingcompiled.Iftheversionis3.30,then__VERSION__willbe"330"(asaninteger). ThemacroGL_core_profileisalwaysdefinedtobe"1".ThemacroGL_compatibility_profileisonlydefinedtobe"1"iftheversionforthisshaderwassettobecompatibility. Reservednames GLSLreservesanynamebeginningwith"gl_";attemptstodefinevariablesorfunctionsthatbeginwiththisstringwillresultinanerror.Also,GLSLhasanumberofkeywords,whichcannotbeusedasidentifiersinanycontext. Types Mainarticle:DataType(GLSL) TheGLSLdefinesanumberoftypes.SomeofthemarefamiliartoC/C++users,whileothersarequitedifferent. Qualifiers Mainarticle:TypeQualifier(GLSL) Variablesdeclaredatglobalandlocalscopecanhaveanumberofqualifiersassociatedwiththem.Mostoftheseareuniquetoshadinglanguages. Expressions GLSLhassomeuniqueexpressiondefinitions. Constantexpression Constantexpressionsareexpressionsthatcanbeevaluatedatcompiletime.ConstantexpressionsinGLSLareexpressionsthatconsistof: Aliteralvalue. Aconst-qualifiedvariable(notafunctionparameter)withanexplicitinitializer,butonlyiftheinitializerisitselfoneofthefollowing: Aconstantexpression. AnInitializerList,whosecomponentsarethemselvesconstantexpressions.Initializerlistsarenotexpressionsthemselves. Theresultofthelength()functionofanarray,butonlyifthearrayhasanexplicitsize(who'ssizemustbeaconstantexpression). Theresultofmostoperators,solongasalltheoperandsarethemselvesconstantexpressions.Theoperatorsnotonthislistareanyassignmentoperators(+=andsoforth),andthecommaoperator. Theresultofaconstructorforatype,butonlyifalloftheargumentstotheconstructorarethemselvesconstantexpressions. Thereturnvalueofanybuilt-infunction,butonlyifalloftheargumentstothefunctionarethemselvesconstantexpressions.OpaqueTypesareneverconstantexpressions.NotethatthefunctionsdFdx,dFdy,fwidth,andtheirCoarseandFinevariationswillreturn0,whengivenaconstantexpressionasanargument. Integralconstantexpression Theseareconstantexpressionsthatresultinaninteger,signedorunsigned. Dynamicallyuniformexpression DynamicallyUniformExpression Coreinversion 4.6 Coresinceversion 4.0 AdynamicallyuniformexpressionisaGLSLexpressioninwhichallinvocationsofthatshaderwithinaparticularsetofinvocationswillhavethesamevalue. OnlyGLSL4.00andabovemakesadistinctionaboutdynamicallyuniformexpressions.Anyrestrictionsyouseethatrequirea"dynamicallyuniformexpression"will,inolderGLSLversionsrequirea"constantexpression". AnexpressioninaGLSLshaderissaidtobedynamicallyuniformif,andonlyif,everyshaderinvocationwithinthesameinvocationgroupwillhavethesamevalue,inthesameorder.Whetheranexpressionisdynamicallyuniformdependsonthevaluesprovided;itcannotalwaysbeapriorideterminedfromashader'scode. Someexpressionsarealwaysdynamicallyuniform,bytherulesofthelanguage.Theseinclude: Constantexpressions Uniformvalues Anyexpression,whichdoesnotinvolveauser-definedfunctioncall,ImageLoadStoreorSSBOoperations,who'sinputvaluesarealldynamicallyuniform Thegl_DrawIDinputtotheVertexShader Otherexpressionsmayormaynotbedynamicallyuniform.Forexample,ashaderstageinputvaluewillusuallynotbedynamicallyuniform.However,ifeveryshaderintherenderingcommandisgiventheexactsameinputvalue,thenitwillbedynamicallyuniform.Itisthevalueoftheexpressionwhichmustbeuniform;everyshaderinvocationmustgetthesamevalue,evenifthatsamevalueisbeingreadfromdifferentmemorylocation. gl_InstanceIDisanexample.Ifyourenderonlyasingleinstance,thengl_InstanceIDwillbedynamicallyuniformforthatrenderingcommand.However,ifyourendermultipleinstancesinthesamecommand,itwillnot.ThesamegoesforInstancedArrayinputvalues. Mostimportantofall,ifyouexecutealoopovervalues,wheretheinitializingexpression,offset,andtestconditionallusedynamicallyuniformexpressions,thentheloopcounteritselfwillbedynamicallyuniform. Whileaccessingtexturesisguaranteedtobedynamicallyuniformifthetexturecoordinatesaredynamicallyuniform,accessingimagevariablesorAtomicCountersisnotnecessarilyso.Thesearemodifiablememory,soeachinvocationmaynotgetthesamevalue.Iftheimagevariableisread-only,thenaccessingitisdynamicallyuniformiftheimagecoordinatesandsofortharedynamicallyuniform. Invocationgroup Dynamicallyuniformexpressionsarebasedonshaderinvocations"withinthesameinvocationgroup."Thedefinitionof"invocationgroup"dependsontheshaderstageinquestion.ForComputeShaders,thescopeisallinvocationswithinaworkgroup.ForshaderslaunchedthroughRenderingCommands,thisgetsmorecomplex. Renderingscopeextendstoallinvocationsofallshaderstagescreatedtoserviceasingledrawingcommand.Thismeansthat,forFragmentShaders,twodistinctprimitivesinarenderingcommandareconsideredpartofthesamescope.Thismeansthatgl_PrimitiveIDisnotdynamicallyuniform(unlessyourenderonlyoneprimitive).Thisisalsowhygl_InstanceIDisonlydynamicallyuniformwhenrenderingasingleinstance;instancedrenderingisconsideredasingledrawingcommand. However,therearedrawingcommandsthatcreatemultiplescopes.TheMultidrawRenderingcommands,includingtheindirectversions,haveseparatescopesfortheirseparatedrawingsub-commands.Sowhiledoinginstancedrenderinginadrawcommandplacesallinstancesinasinglescope,renderingmultipletimeswithamultidrawcommandwithabaseinstancecreatesmultiplescopes,oneperinternaldraw. Note:TheaboveinformationinthissectionisbasedonGLSL4.60.Assuch,thismaynotbeentirelycorrectforearlierversions;theydefinedtheideaof"dynamicallyuniform",butdidn'treallygointoexplicitdetails.However,sincetheyarebasedmainlyonthehardwareratherthanthecompiler,andthisdefinitionisreallyaboutthebehaviorofthehardware,itisnotunreasonabletoassumethattheyapplytoolderGLSLversionsaswell. Uses ThereareplaceswhereGLSLrequirestheexpressiontobedynamicallyuniform.Allofthefollowingmustuseadynamicallyuniformexpression: Thearrayindexforarraysofopaquetypes. Theindextobuffer-backedinterfaceblockarrays. InComputeShaders,theexpressionsleadingtotheexecutionofabarrier()call.Soifthereisalooporaconditionalstatementorsomesuch,alloftheseconditionsmustbedynamicallyuniformexpressions,sothateverycomputeshaderinvocationencounterseverybarrier()statementinthesamesequenceandthesamenumberoftimes. Examples V·E Thisexamplecodeshowswhatareandarenotdynamicallyuniformexpressions. invec3fromPrevious; inuvec2fromRange; constintfoo=5; constuvec2range=uvec2(2,5); uniformvec2pairs; uniformsampler2dtex; voidmain() { foo;//constantexpressionsaredynamicallyuniform. uintvalue=21;//'value'isdynamicallyuniform. value=range.x;//stilldynamicallyuniform. value=range.y+fromRange.y;//notdynamicallyuniform;currentcontentscomefromanon-dynamicallyuniformsource. value=4;//dynamicallyuniformagain. if(fromPrevious.y<3.14) value=12; value;//NOTdynamicallyuniform.Currentcontentsdependon'fromPrevious',aninputvariable. floatnumber=abs(pairs.x);//'number'isdynamicallyuniform. number=sin(pairs.y);//stilldynamicallyuniform. number=cos(fromPrevious.x);//notdynamicallyuniform. vec4colors=texture(tex,pairs.xy);//dynamicallyuniform,eventhoughitcomesfromatexture. //Itusesthesametexturecoordinate,thusgettingthesametexeleverytime. colors=texture(tex,fromPrevious.xy);//notdynamicallyuniform. for(inti=range.x;i



請為這篇文章評分?