However, unlike ANSI C, main() does not return an integer value; ... GLSL switch statements also support “fall-through” cases—case ...
SUMMERREAD-A-THON
Save35%onbooks&eBookswithcodeREADATHON.Shopnow.
Home
>
Articles
ShaderFundamentals
Oct24,2016
📄Contents
␡
ShadersandOpenGL
OpenGL'sProgrammablePipeline
AnOverviewoftheOpenGLShadingLanguage
InterfaceBlocks
CompilingShaders
ShaderSubroutines
SeparateShaderObjects
SPIR-V
⎙Print
+ShareThis
Thischapterisfromthebook
OpenGLProgrammingGuide:TheOfficialGuidetoLearningOpenGL,Version4.5withSPIR-V,9thEdition
LearnMore
Buy
OpenGLProgrammingGuide:TheOfficialGuidetoLearningOpenGL,Version4.5withSPIR-V,9thEdition
LearnMore
Buy
AnOverviewoftheOpenGLShadingLanguage
ThissectionprovidesanoverviewoftheshadinglanguageusedwithinOpenGL.GLSLsharesmanytraitswithC++andJava,andisusedforauthoringshadersforallthestagessupportedinOpenGL,althoughcertainfeaturesareavailableonlyforparticulartypesofshaders.WewillfirstdescribeGLSL’srequirements,types,andotherlanguageconstructsthataresharedbetweenthevariousshaderstages,andthendiscussthefeaturesuniquetoeachtypeofshader.
CreatingShaderswithGLSL
Here,wedescribehowtocreateacompleteshader.
TheStartingPoint
Ashaderprogram,justlikeaCprogram,startsexecutioninmain().EveryGLSLshaderprogrambeginslifeasfollows:
#version330core
void
main()
{
//Yourcodegoeshere
}
The//constructisacommentandterminatesattheendofthecurrentline,justlikeinC.Additionally,C-type,multi-linecomments—the/*and*/type—arealsosupported.However,unlikeANSIC,main()doesnotreturnanintegervalue;itisdeclaredvoid.Also,aswithCanditsderivativelanguages,statementsareterminatedwithasemicolon.WhilethisisaperfectlylegalGLSLprogramthatcompilesandevenruns,itsfunctionalityleavessomethingtobedesired.Toaddalittlemoreexcitementtoourshaders,we’llcontinuebydescribingvariablesandtheiroperation.
DeclaringVariables
GLSLisatypedlanguage;everyvariablemustbedeclaredandhaveanassociatedtype.VariablenamesconformtothesamerulesasthoseforC:Youcanuseletters,numbers,andtheunderscorecharacter(_)tocomposevariablenames.However,adigitcannotbethefirstcharacterinavariablename.Similarly,variablenamescannotcontainconsecutiveunderscores;thosenamesarereservedinGLSL.
Table2.1showsthebasictypesavailableinGLSL.
Table2.1BasicDataTypesinGLSL
Type
Description
float
IEEE32-bitfloating-pointvalue
double
IEEE64-bitfloating-pointvalue
int
signedtwo´s-complement32-bitintegervalue
uint
unsigned32-bitintegervalue
bool
Booleanvalue
Thesetypes(andlater,aggregatetypescomposedofthese)arealltransparent.Thatis,theirinternalformisexposedandtheshadercodegetstoassumewhattheylooklikeinternally.
Anadditionalsetoftypes,theopaquetypes,donothavetheirinternalformexposed.Theseincludesamplertypes,imagetypes,andatomiccountertypes.Theydeclarevariablesusedasopaquehandlesforaccessingtexturemaps,images,andatomiccounters,asdescribedinChapter4,“Color,Pixels,andFragments.”
ThevarioustypesofsamplersandtheirusesarediscussedinChapter6,“TexturesandFramebuffers.”
VariableScoping
Whileallvariablesmustbedeclared,theymaybedeclaredanytimebeforetheiruse(justasinC++).ThescopingrulesofGLSL,whichcloselyparallelthoseofC++,areasfollows:
Variablesdeclaredoutsideofanyfunctiondefinitionhaveglobalscopeandarevisibletoallsubsequentfunctionswithintheshaderprogram.
Variablesdeclaredwithinasetofcurlybraces(e.g.,functiondefinition,blockfollowingaloopor“if”statement,etc.)existwithinthescopeofthosebracesonly.
Loopiterationvariables,suchasiintheloop
for(inti=0;i<10;++i){
//loopbody
}
arescopedonlyforthebodyoftheloop.
VariableInitialization
Variablesmayalsobeinitializedwhendeclared.Forexample:
int i,numParticles=1500;
float force,g=-9.8;
bool falling=true;
double pi=3.1415926535897932384626LF;
Integerliteralconstantsmaybeexpressedasoctal,decimal,orhexadecimalvalues.Anoptionalminussignbeforeanumericvaluenegatestheconstant,andatrailing‘u’or‘U’denotesanunsignedintegervalue.
Floating-pointliteralsmustincludeadecimalpoint,unlessdescribedinscientificformat,asin3E-7.(However,therearemanysituationswhereanintegerliteralwillbeimplicitlyconvertedtoafloating-pointvalue.)Additionally,theymayoptionallyincludean‘f’or‘F’suffixasinConafloatliteral.Youmustincludeasuffixof‘lF’or‘LF’tomakealiteralhavetheprecisionofadouble.
BooleanvaluesareeithertrueorfalseandcanbeinitializedtoeitherofthosevaluesorastheresultofanoperationthatresolvestoaBooleanexpression.
Constructors
Asmentioned,GLSLismoretypesafethanC++,havingfewerimplicitconversionbetweenvalues.Forexample,
intf=false;
willresultinacompilationerrorduetoassigningaBooleanvaluetoanintegervariable.TypeswillbeimplicitlyconvertedasshowninTable2.2.
Table2.2ImplicitConversionsinGLSL
TypeNeeded
CanBeImplicitlyConvertedFrom
uint
int
float
int,uint
double
int,uint,float
Thesetypeconversionsworkforscalars,vectors,andmatricesofthesetypes.Conversionswillneverchangewhethersomethingisavectororamatrix,orhowmanycomponentsithas.Conversionsalsodon’tapplytoarraysorstructures.
Anyotherconversionofvaluesrequiresexplicitconversionusingaconversionconstructor.Aconstructor,asinotherlanguageslikeC++,isafunctionwiththesamenameasatype,whichreturnsavalueofthattype.Forexample,
floatf=10.0;
int ten=int(f);
usesanintconversionconstructortodotheconversion.Likewise,theothertypesalsohaveconversionconstructors:float,double,uint,bool,andvectorsandmatricesofthesetypes.Eachacceptsmultipleothertypestoexplicitlyconvertfrom.ThesefunctionsalsoillustrateanotherfeatureofGLSL:functionoverloading,wherebyeachfunctiontakesvariousinputtypes,butallusethesamebasefunctionname.Wewilldiscussmoreonfunctionsinabit.
AggregateTypes
GLSL’sbasictypescanbecombinedtobettermatchcoreOpenGL’sdatavaluesandtoeasecomputationaloperations.
First,GLSLsupportsvectorsoftwo,three,orfourcomponentsforeachofthebasictypesofbool,int,uint,float,anddouble.Also,matricesoffloatanddoubleareavailable.Table2.3liststhevalidvectorandmatrixtypes.
Table2.3GLSLVectorandMatrixTypes
BaseType
2DVec
3DVec
4DVec
MatrixTypes
float
vec2
vec3
vec4
mat2mat3mat4mat2x2mat2x3mat2x4mat3x2mat3x3mat3x4mat4x2mat4x3mat4x4
double
dvec2
dvec3
dvec4
dmat2dmat3dmat4dmat2x2dmat2x3dmat2x4dmat3x2dmat3x3dmat3x4dmat4x2dmat4x3dmat4x4
int
ivec2
ivec3
ivec4
‐
uint
uvec2
uvec3
uvec4
‐
bool
bvec2
bvec3
bvec4
‐
Matrixtypesthatlistbothdimensions,suchasmat4x3,usethefirstvaluetospecifythenumberofcolumns,thesecondthenumberofrows.
Variablesdeclaredwiththesetypescanbeinitializedsimilartotheirscalarcounterparts:
vec3velocity=vec3(0.0,2.0,3.0);
Convertingbetweentypesisequallyaccessible:
ivec3steps=ivec3(velocity);
Vectorconstructorscanalsobeusedtotruncateorlengthenavector.Ifalongervectorispassedintotheconstructorofasmallervector,thevectoristruncatedtotheappropriatelength.
vec4color;
vec3RGB=vec3(color);//nowRGBonlyhasthreeelements
Scalarvaluescanbepromotedtovectors,butthat’stheonlywayavectorconstructortakesfewercomponentsthanitssizeindicates:
vec3white=vec3(1.0); //white=(1.0,1.0,1.0)
vec4translucent=vec4(white,0.5);
Matricesareconstructedinthesamemannerandcanbeinitializedtoeitheradiagonalmatrixorafullypopulatedmatrix.Inthecaseofdiagonalmatrices,asinglevalueispassedintotheconstructor,andthediagonalelementsofthematrixaresettothatvalue,withallothersbeingsettozero,asin
Matricescanalsobecreatedbyspecifyingthevalueofeveryelementinthematrixintheconstructor.Valuescanbespecifiedbycombinationsofscalarsandvectorsaslongasenoughvaluesareprovidedandeachcolumnisspecifiedinthesamemanner.Additionally,matricesarespecifiedincolumn-majororder,meaningthevaluesareusedtopopulatecolumnsbeforerows(whichistheoppositeofhowCinitializestwo-dimensionalarrays).
Forexample,wecouldinitializea3×3matrixinanyofthefollowingways:
mat3M=mat3(1.0,2.0,3.0,
4.0,5.0,6.0,
7.0,8.0,9.0);
vec3column1=vec3(1.0,2.0,3.0);
vec3column2=vec3(4.0,5.0,6.0);
vec3column3=vec3(7.0,8.0,9.0);
mat3M=mat3(column1,column2,column3);
oreven
vec2column1=vec2(1.0,2.0);
vec2column2=vec2(4.0,5.0);
vec2column3=vec2(7.0,8.0);
mat3M=mat3(column1,3.0,
column2,6.0,
column3,9.0);
allyieldingthesamematrix,
AccessingElementsinVectorsandMatrices
Theindividualelementsofvectorsandmatricescanbeaccessedandassigned.Vectorssupporttwotypesofelementaccess:anamed-componentmethodandanarray-likemethod.Matricesuseatwo-dimensionalarray-likemethod.
Componentsofavectorcanbeaccessedbyname,asin
floatred=color.r;
floatv_y=velocity.y;
orbyusingazero-basedindexscheme.Thefollowingyieldidenticalresultstothepreviouslisting:
floatred=color[0];
floatv_y=velocity[1];
Infact,asshowninTable2.4,therearethreesetsofcomponentnames,allofwhichdothesamething.Themultiplesetsareusefulforclarifyingtheoperationsthatyou’redoing.
Table2.4VectorComponentAccessors
ComponentAccessors
Description
(x,y,z,w)
Componentsassociatedwithpositions
(r,g,b,a)
Componentsassociatedwithcolors
(s,t,p,q)
Componentsassociatedwithtexturecoordinates
Acommonuseforcomponent-wiseaccesstovectorsisforswizzlingcomponents,asyoumightdowithcolors,perhapsforcolorspaceconversion.Forexample,youcoulddothefollowingtospecifyaluminancevaluebasedontheredcomponentofaninputcolor:
vec3luminance=color.rrr;
Likewise,ifyouneededtomovecomponentsaroundinavector,youmightdo
color=color.abgr;//reversethecomponentsofacolor
Theonlyrestrictionisthatonlyonesetofcomponentscanbeusedwithavariableinonestatement.Thatis,youcan’tdo
vec4color=otherColor.rgz;//Error:'z'isfromadifferentgroup
Also,acompile-timeerrorwillberaisedifyouattempttoaccessanelementthat’soutsidetherangeofthetype.Forexample,
vec2pos;
floatzPos=pos.z;//Error:no'z'componentin2Dvectors
Matrixelementscanbeaccessedusingthearraynotation.Eitherasinglescalarvalueoranarrayofelementscanbeaccessedfromamatrix:
mat4m=mat4(2.0);
vec4zVec=m[2]; //getcolumn2ofthematrix
floatyScale=m[1][1];//orm[1].yworksaswell
Structures
Youcanalsologicallygroupcollectionsofdifferenttypesintoastructure.Structuresareconvenientforpassinggroupsofassociateddataintofunctions.Whenastructureisdefined,itautomaticallycreatesanewtypeandimplicitlydefinesaconstructorfunctionthattakesthetypesoftheelementsofthestructureasparameters.
structParticle{
floatlifetime;
vec3position;
vec3velocity;
};
Particlep=Particle(10.0,pos,vel);//pos,velarevec3s
Likewise,toreferenceelementsofastructure,usethefamiliar“dot”notationasyouwouldinC.
Arrays
GLSLalsosupportsarraysofanytype,includingstructures.AswithC,arraysareindexedusingbrackets([]).Therangeofelementsinanarrayofsizenis0...n–1.UnlikeinC,however,neithernegativearrayindicesnorpositiveindicesoutofrangearepermitted.AsofGLSL4.3,arrayscanbemadeoutofarrays,providingawaytohandlemultidimensionaldata.However,GLSL4.2andearlierversionsdonotallowarraysofarraystobecreated(thatis,youcannotcreateamultidimensionalarray).
Arrayscanbedeclaredsizedorunsized.Youmightuseanunsizedarrayasaforwarddeclarationofanarrayvariableandlaterredeclareittotheappropriatesize.Arraydeclarationsusethebracketnotation,asin
float coeff[3];//anarrayof3floats
float[3] coeff;//samething
int indices[];//unsized.Redeclarelaterwithasize
Arraysarefirst-classtypesinGLSL,meaningtheyhaveconstructorsandcanbeusedasfunctionparametersandreturntypes.Tostaticallyinitializeanarrayofvalues,youwoulduseaconstructorinthefollowingmanner:
floatcoeff[3]=float[3](2.38,3.14,42.0);
Thedimensionvalueontheconstructorisoptional.
Additionally,similartoJava,GLSLarrayshaveanimplicitmethodforreportingtheirnumberofelements:thelength()method.Ifyouwouldliketooperateonallthevaluesinanarray,hereisanexampleusingthelength()method:
for(inti=0;i>
integer
Bit-wiseoperations
7
<><=>=
arithmetic
Relationaloperations
8
==!=
any
Equalityoperations
9
&
integer
Bit-wiseand
10
∧
integer
Bit-wiseexclusiveor
11
|
integer
Bit-wiseinclusiveor
12
&&
bool
Logicalandoperation
13
∧∧
bool
Logicalexclusive-oroperation
14
||
bool
Logicaloroperation
15
a?b:c
bool?any:any
Ternaryselectionoperation(inline“if„operation;if(a)then(b)else(c))
16
=+=-=*=/=%=<<=>>=&=∧=|=
anyarithmeticarithmeticintegerinteger
AssignmentArithmeticassignment
17
,(comma)
any
Sequenceofoperations
OverloadedOperators
MostoperatorsinGLSLareoverloaded,meaningthattheyoperateonavariedsetoftypes.Specifically,arithmeticoperations(includingpre-andpost-incrementand-decrement)forvectorsandmatricesarewelldefinedinGLSL.Forexample,tomultiplyavectorandamatrix(recallingthattheorderofoperandsisimportant;matrixmultiplicationisnoncommutative,forallyoumathheads),usethefollowingoperation:
vec3v;
mat3m;
vec3result=v*m;
Thenormalrestrictionsapply,thatthedimensionalityofthematrixandthevectormustmatch.Additionally,scalarmultiplicationwithavectorormatrixwillproducetheexpectedresult.Onenotableexceptionisthatthemultiplicationoftwovectorswillresultincomponent-wisemultiplicationofcomponents;however,multiplyingtwomatriceswillresultinnormalmatrixmultiplication.
vec2a,b,c;
mat2m,u,v;
c=a*b;// c=(a.x*b.x,a.y*b.y)
m=u*v;// m=(u00*v00+u01*v10 u00*v01+u01*v11
// u01*v00+u11*v10 u10*v01+u11*v11)
Additionalcommonvectoroperations(e.g.,dotandcrossproducts)aresupportedbyfunctioncalls,aswellasvariousper-componentoperationsonvectorsandmatrices.
ControlFlow
GLSL’slogicalcontrolstructuresarethepopularif-elseandswitchstatements.AswiththeClanguage,theelseclauseisoptional,andmultiplestatementsrequireablock.
if(truth){
//trueclause
}
else{
//falseclause
}
SimilartothesituationinC,switchstatementsareavailable(startingwithGLSL1.30)intheirfamiliarform:
switch(int_value){
casen:
//statements
break;
casem:
//statements
break;
default:
//statements
break;
}
GLSLswitchstatementsalsosupport“fall-through”cases—casestatementsthatdonotendwithbreakstatements.Eachcasedoesrequiresomestatementtoexecutebeforetheendoftheswitch(beforetheclosingbrace).Also,unlikeinC++,nostatementsareallowedbeforethefirstcase.Ifnocasematchestheswitchandadefaultlabelispresent,thenitisexecuted.
LoopingConstructs
GLSLsupportsthefamiliarCformoffor,while,anddo...whileloops.
Theforlooppermitsthedeclarationoftheloopiterationvariableintheinitializationclauseoftheforloop.Thescopeofiterationvariablesdeclaredinthismannerisonlyforthelifetimeoftheloop.
for(inti=0;i<10;++i){
...
}
while(n<10){
...
}
do{
...
}while(n<10);
Control-FlowStatements
AdditionalcontrolstatementsbeyondconditionalsandloopsareavailableinGLSL.Table2.7describesavailablecontrol-flowstatements.
Table2.7GLSLControl-FlowStatements
Statement
Description
break
Terminatesexecutionoftheblockofaloopandcontinuesexecutionafterthescopeofthatblock.
continue
Terminatesthecurrentiterationoftheenclosingblockofaloop,resumingexecutionwiththenextiterationoftheloop.
return[result]
Returnsfromthecurrentfunction,optionallyprovidingavaluetobereturnedfromthefunction(assumingreturnvaluematchesthereturntypeoftheenclosingfunction).
discard
Discardsthecurrentfragmentandceasesshaderexecution.Discardstatementsarevalidonlyinfragmentshaderprograms.
Thediscardstatementisavailableonlyinfragmentprograms.Theexecutionofthefragmentshadermaybeterminatedattheexecutionofthediscardstatement,butthisisimplementation-dependent.
Functions
Functionspermityoutoreplaceoccurrencesofcommoncodewithafunctioncall.This,ofcourse,allowsforsmallercodeandfewerchancesforerrors.GLSLdefinesanumberofbuilt-infunctions,whicharelistedinAppendixC,aswellassupportforuser-definedfunctions.User-definedfunctionscanbedefinedinasingleshaderobjectandreusedinmultipleshaderprograms.
Declarations
FunctiondeclarationsyntaxisverysimilartoC,withtheexceptionoftheaccessmodifiersonvariables:
returnTypefunctionName([accessModifier]type1variable1,
[accessModifier]type2variable2,
...)
{
//functionbody
returnreturnValue;//unlessreturnTypeisvoid
}
Functionnamescanbeanycombinationofletters,numbers,andtheunderscorecharacter,withtheexceptionthatitcanneitherbeginwithadigitnorwithgl_norcontainconsecutiveunderscores.
Returntypescanbeanybuilt-inGLSLtypeoruser-definedstructureorarraytype.Arraysasreturnvaluesmustexplicitlyspecifytheirsize.Ifafunctiondoesn’treturnavalue,itsreturntypeisvoid.
Parameterstofunctionscanalsobeofanytype,includingarrays(whichmustspecifytheirsize).
Functionsmustbeeitherdeclaredwithaprototypeordefinedwithabodybeforetheyarecalled.JustasinC++,thecompilermusthaveseenthefunction’sdeclarationbeforeitsuse,oranerrorwillberaised.Ifafunctionisusedinashaderobjectotherthantheonewhereit’sdefined,aprototypemustbedeclared.Aprototypeismerelythefunction’ssignaturewithoutitsaccompanyingbody.Here’sasimpleexample:
floatHornerEvalPolynomial(floatcoeff[10],floatx);
ParameterQualifiers
WhilefunctionsinGLSLareabletomodifyandreturnvaluesaftertheirexecution,there’snoconceptofapointerorreference,asinCorC++.Rather,parametersoffunctionshaveassociatedparameterqualifiersindicatingwhetherthevalueshouldbecopiedinto,oroutof,afunctionafterexecution.Table2.8describestheavailableparameterqualifiersinGLSL.
Table2.8GLSLFunctionParameterAccessModifiers
AccessModifier
Description
in
Valuecopiedintoafunction(defaultifnotspecified)
constin
Read-onlyvaluecopiedintoafunction
out
Valuecopiedoutofafunction(undefineduponentranceintothefunction)
inout
Valuecopiedintoandoutofafunction
Theinkeywordisoptional.Ifavariabledoesnotincludeanaccessmodifier,aninmodifierisimplicitlyaddedtotheparameter’sdeclaration.However,ifthevariable’svalueneedstobecopiedoutofafunction,itmusteitherbetaggedwithanout(forcopyout-onlyvariables)oraninout(foravariablebothcopiedinandcopiedout)modifier.Writingtoavariablenottaggedwithoneofthesemodifierswillgenerateacompile-timeerror.
Additionally,toverifyatcompiletimethatafunctiondoesn’tmodifyaninput-onlyvariable,addingaconstinmodifierwillcausethecompilertocheckthatthevariableisnotwrittentointhefunction.Ifyoudon’tdothisanddowritetoaninput-onlyvariable,thewriteonlymodifiesthelocalcopyinthefunction.
ComputationalInvariance
GLSLdoesnotguaranteethattwoidenticalcomputationsindifferentshaderswillresultinexactlythesamevalue.ThesituationisnodifferentthanforcomputationalapplicationsexecutingontheCPU,wherethechoiceofoptimizationsmayresultintinydifferencesinresults.Thesetinyerrorsmaybeanissueformultipassalgorithmsthatexpectpositionstobecomputedexactlythesameforeachshaderpass.GLSLhastwomethodsforenforcingthistypeofinvariancebetweenshaders,usingtheinvariantorprecisekeywords.
Bothofthesemethodswillcausecomputationsdonebythegraphicsdevicetocreatereproducibility(invariance)inresultsofthesameexpression.However,theydonothelpreproducethesameresultsbetweenthehostandthegraphicsdevice.Compile-timeconstantexpressionsarecomputedonthecompiler’shost,andthereisnoguaranteethatthehostcomputesinexactlythesamewayasthegraphicsdevice.Forexample:
uniformfloatten; //applicationsetsthisto10.0
constfloatf=sin(10.0);//computedoncompilerhost
floatg=sin(ten); //computedongraphicsdevice
voidmain()
{
if(f==g) //fandgmightbenotequal
;
}
Inthisexample,itwouldnotmatterifinvariantorprecisewasusedonanyofthevariablesinvolved,astheyaffectonlytwocomputationsdoneonthegraphicsdevice.
TheinvariantQualifier
Theinvariantqualifiermaybeappliedtoanyshaderoutputvariable.Itwillguaranteethatiftwoshaderinvocationseachsettheoutputvariablewiththesameexpressionandthesamevaluesforthevariablesinthatexpression,bothwillcomputethesamevalue.
Theoutputvariabledeclaredasinvariantmaybeabuilt-invariableorauser-definedone.Forexample:
invariantgl_Position;
invariantcentroidoutvec3Color;
Asyoumayrecall,outputvariablesareusedtopassdatafromonestagetothenext.Theinvariantkeywordmaybeappliedatanytimebeforeuseofthevariableintheshaderandmaybeusedtomodifybuilt-invariables.Thisisdonebydeclaringthevariableonlywithinvariant,aswasshownearlierforgl_Position.
Fordebugging,itmaybeusefultoimposeinvarianceonallvaryingvariablesinshader.Thiscanbeaccomplishedbyusingthevertexshaderpreprocessorpragma.
#pragmaSTDGLinvariant(all)
Globalinvarianceinthismannerisusefulfordebugging;however,itmaylikelyhaveanimpactontheshader’sperformance.GuaranteeinginvarianceusuallydisablesoptimizationsthatmayhavebeenperformedbytheGLSLcompiler.
ThepreciseQualifier
Theprecisequalifiermaybeappliedtoanycomputedvariableorfunctionreturnvalue.Despiteitsname,itspurposeisnottoincreaseprecision,buttoincreasereproducibilityofacomputation.Itismostlyusedintessellationshaderstoavoidformingcracksinyourgeometry.TessellationshadingingeneralisdescribedinChapter9,“TessellationShaders,”andthereisadditionaldiscussioninthatchapteraboutausecaseforprecisequalification.
Generally,youusepreciseinsteadofinvariantwhenyouneedtogetthesameresultfromanexpression,evenifvaluesfeedingtheexpressionarepermutedinawaythatshouldnotmathematicallyaffecttheresult.Forexample,thefollowingexpressionshouldgetthesameresultifthevaluesforaandbareexchanged.Itshouldalsogetthesameresultifthevaluesforcanddandexchanged,orifbothaandcareexchangedandbanddareexchanged,andsoon.
Location=a*b+c*d;
Theprecisequalifiermaybeappliedtoabuilt-invariable,uservariable,orfunctionreturnvalue.
precisegl_Position;
preciseoutvec3Location;
precisevec3subdivide(vec3P1,vec3P2){...}
Theprecisekeywordmaybeappliedatanytimebeforeuseofthevariableintheshaderandmaybeusedtomodifypreviouslydeclaredvariables.
Onepracticalimpactinacompilerofusingpreciseisanexpressionliketheoneabovecannotbeevaluatedusingtwodifferentmethodsofmultiplicationforthetwomultiplyoperations—forexample,amultiplyinstructionforthefirstmultiplyandafusedmultiply-and-addinstructionforthesecondmultiply.Thisisbecausethesetwoinstructionswillgetslightlydifferentresultsforthesamevalues.Becausethatwasdisallowedbyprecise,thecompilerispreventedfromdoingthis.Becauseuseoffusedmultiply-and-addinstructionsisimportanttoperformance,itwouldbeunfortunatetocompletelydisallowthem.Sothereisabuilt-infunctioninGLSL,fma(),thatyoucanusetoexplicitlysaythisisokay.
preciseoutfloatresult;
...
floatf=c*d;
floatresult=fma(a,b,f);
Ofcourse,youdothatonlyifyouweren’tgoingtohavethevaluesofaandcpermuted,asyouwouldbedefeatingthepurposeofusingprecise.
ShaderPreprocessor
ThefirststepincompilationofaGLSLshaderisparsingbythepreprocessor.SimilartotheCpreprocessor,thereareanumberofdirectivesforcreatingconditionalcompilationblocksanddefiningvalues.However,unlikeintheCpreprocessor,thereisnofileinclusion(#include).
PreprocessorDirectives
Table2.9liststhepreprocessordirectivesacceptedbytheGLSLpreprocessorandtheirfunctions.
Table2.9GLSLPreprocessorDirectives
PreprocessorDirective
Description
#define
Controlthedefinitionofconstantsand
#undef
macrossimilartotheCpreprocessor.
#if
Conditionalcodemanagementsimilar
#ifdef
totheCpreprocessor,includingthedefinedoperator.
#ifndef
#else
Conditionalexpressionsevaluateinteger
#elif
expressionsanddefinedvalues
#endif
(asspecifiedby#define)only.
#errortext
Causethecompilertoinserttext(uptothefirstnewlinecharacter)intotheshaderinformationlog.
#pragmaoptions
Controlcompilerspecificoptions.
#extensionoptions
SpecifycompileroperationwithrespecttospecifiedGLSLextensions.
#versionnumber
MandateaspecificversionofGLSLversionsupport.
#lineoptions
Controldiagnosticlinenumbering.
MacroDefinition
TheGLSLpreprocessorallowsmacrodefinitioninmuchthesamemannerastheCpreprocessor,withtheexceptionofthestringsubstitutionandconcatenationfacilities.Macrosmightdefineasinglevalue,asin
#defineNUM_ELEMENTS10
orwithparameterslike
#defineLPos(n)gl_LightSource[(n)].position
Additionally,thereareseveralpredefinedmacrosforaidingindiagnosticmessages(thatyoumightissuewiththe#errordirective,forexample),asshowninTable2.10.
Table2.10GLSLPreprocessorPredefinedMacros
MacroName
Description
_LINE_
Linenumberdefinedbyonemorethanthenumberofnewlinecharactersprocessedandmodifiedbythe#linedirective
_FILE_
Sourcestringnumbercurrentlybeingprocessed
_VERSION_
IntegerrepresentationoftheOpenGLShadingLanguageversion
Likewise,macros(excludingthosedefinedbyGLSL)maybeundefinedbyusingthe#undefdirective.Forexample,
#undefLPos
PreprocessorConditionals
IdenticaltotheprocessingbytheCpreprocessor,theGLSLpreprocessorprovidesconditionalcodeinclusionbasedonmacrodefinitionandintegerconstantevaluation.
Macrodefinitionmaybedeterminedintwoways.Usethe#ifdefdirective:
#ifdefNUM_ELEMENTS
...
#endif
Orusethedefinedoperatorwiththe#ifor#elifdirectives:
#ifdefined(NUM_ELEMENTS)&&NUM_ELEMENTS>3
...
#elifNUM_ELEMENTS<7
...
#endif
CompilerControl
The#pragmadirectiveprovidesthecompileradditionalinformationregardinghowyouwouldlikeyourshaderscompiled.
OptimizationCompilerOption
Theoptimizeoptioninstructsthecompilertoenableordisableoptimizationoftheshaderfromthepointwherethedirectiveresidesforwardintheshadersource.Youcanenableordisableoptimizationbyissuingeither
#pragmaoptimize(on)
or
#pragmaoptimize(off)
respectively.Theseoptionsmaybeissuedonlyoutsideofafunctiondefinition.Bydefault,optimizationisenabledforallshaders.
DebugCompilerOption
Thedebugoptionenablesordisablesadditionaldiagnosticoutputoftheshader.Youcanenableordisabledebuggingbyissuingeither
#pragmadebug(on)
or
#pragmadebug(off)
respectively.Aswiththeoptimizeoption,theseoptionsmaybeissuedonlyoutsideofafunctiondefinition,andbydefault,debuggingisdisabledforallshaders.
GlobalShader-CompilationOption
Onefinal#pragmadirectivethatisavailableisSTDGL.Thisoptioniscurrentlyusedtoenableinvarianceintheoutputofvaryingvalues.
ExtensionProcessinginShaders
GLSL,likeOpenGLitself,maybeenhancedbyextensions.AsvendorsmayincludeextensionsspecifictotheirOpenGLimplementation,it’susefultohavesomecontrolovershadercompilationinlightofpossibleextensionsthatashadermayuse.
TheGLSLpreprocessorusesthe#extensiondirectivetoprovideinstructionstotheshadercompilerregardinghowextensionavailabilityshouldbehandledduringcompilation.Foranyorallextensions,youcanspecifyhowyouwouldlikethecompilertoproceedwithcompilation:
#extensionextension_name:
forasingleextension,or
#extensionall:
whichaffectsthebehaviorofallextensions.
TheoptionsavailableareshowninTable2.11
Table2.11GLSLExtensionDirectiveModifiers
Directive
Description
require
Flaganerroriftheextensionisnotsupportedoriftheall-extensionspecificationisused.
enable
Giveawarningiftheparticularextensionsspecifiedarenotsupported,orflaganerroriftheall-extensionspecificationisused.
warn
Giveawarningiftheparticularextensionsspecifiedarenotsupported,orgiveawarningifanyextensionuseisdetectedduringcompilation.
disable
Disablesupportfortheparticularextensionslisted(thatis,havethecompileractasiftheextensionisnotsupportedevenifitis)orallextensionsifallispresent,issuingwarningsanderrorsasiftheextensionwerenotpresent.
+ShareThis
🔖SaveToYourAccount
InformITPromotionalMailings&SpecialOffers
⚠
IwouldliketoreceiveexclusiveoffersandhearaboutproductsfromInformITanditsfamilyofbrands.Icanunsubscribeatanytime.
PrivacyNotice
Overview
PearsonEducation,Inc.,221RiverStreet,Hoboken,NewJersey07030,(Pearson)presentsthissitetoprovideinformationaboutproductsandservicesthatcanbepurchasedthroughthissite.
Thisprivacynoticeprovidesanoverviewofourcommitmenttoprivacyanddescribeshowwecollect,protect,useandsharepersonalinformationcollectedthroughthissite.PleasenotethatotherPearsonwebsitesandonlineproductsandserviceshavetheirownseparateprivacypolicies.
CollectionandUseofInformation
Toconductbusinessanddeliverproductsandservices,Pearsoncollectsandusespersonalinformationinseveralwaysinconnectionwiththissite,including:
QuestionsandInquiries
Forinquiriesandquestions,wecollecttheinquiryorquestion,togetherwithname,contactdetails(emailaddress,phonenumberandmailingaddress)andanyotheradditionalinformationvoluntarilysubmittedtousthroughaContactUsformoranemail.Weusethisinformationtoaddresstheinquiryandrespondtothequestion.
OnlineStore
Forordersandpurchasesplacedthroughouronlinestoreonthissite,wecollectorderdetails,name,institutionnameandaddress(ifapplicable),emailaddress,phonenumber,shippingandbillingaddresses,credit/debitcardinformation,shippingoptionsandanyinstructions.Weusethisinformationtocompletetransactions,fulfillorders,communicatewithindividualsplacingordersorvisitingtheonlinestore,andforrelatedpurposes.
Surveys
Pearsonmayofferopportunitiestoprovidefeedbackorparticipateinsurveys,includingsurveysevaluatingPearsonproducts,servicesorsites.Participationisvoluntary.Pearsoncollectsinformationrequestedinthesurveyquestionsandusestheinformationtoevaluate,support,maintainandimproveproducts,servicesorsites,developnewproductsandservices,conducteducationalresearchandforotherpurposesspecifiedinthesurvey.ContestsandDrawings
Occasionally,wemaysponsoracontestordrawing.Participationisoptional.Pearsoncollectsname,contactinformationandotherinformationspecifiedontheentryformforthecontestordrawingtoconductthecontestordrawing.Pearsonmaycollectadditionalpersonalinformationfromthewinnersofacontestordrawinginordertoawardtheprizeandfortaxreportingpurposes,asrequiredbylaw.
Newsletters
Ifyouhaveelectedtoreceiveemailnewslettersorpromotionalmailingsandspecialoffersbutwanttounsubscribe,[email protected].
ServiceAnnouncements
Onrareoccasionsitisnecessarytosendoutastrictlyservicerelatedannouncement.Forinstance,ifourserviceistemporarilysuspendedformaintenancewemightsendusersanemail.Generally,usersmaynotopt-outofthesecommunications,thoughtheycandeactivatetheiraccountinformation.However,thesecommunicationsarenotpromotionalinnature.
CustomerService
Wecommunicatewithusersonaregularbasistoproviderequestedservicesandinregardtoissuesrelatingtotheiraccountwereplyviaemailorphoneinaccordancewiththeusers'wisheswhenausersubmitstheirinformationthroughourContactUsform.OtherCollectionandUseofInformation
ApplicationandSystemLogs
Pearsonautomaticallycollectslogdatatohelpensurethedelivery,availabilityandsecurityofthissite.Logdatamayincludetechnicalinformationabouthowauserorvisitorconnectedtothissite,suchasbrowsertype,typeofcomputer/device,operatingsystem,internetserviceproviderandIPaddress.Weusethisinformationforsupportpurposesandtomonitorthehealthofthesite,identifyproblems,improveservice,detectunauthorizedaccessandfraudulentactivity,preventandrespondtosecurityincidentsandappropriatelyscalecomputingresources.
WebAnalytics
Pearsonmayusethirdpartywebtrendanalyticalservices,includingGoogleAnalytics,tocollectvisitorinformation,suchasIPaddresses,browsertypes,referringpages,pagesvisitedandtimespentonaparticularsite.Whiletheseanalyticalservicescollectandreportinformationonananonymousbasis,theymayusecookiestogatherwebtrendinformation.TheinformationgatheredmayenablePearson(butnotthethirdpartywebtrendservices)tolinkinformationwithapplicationandsystemlogdata.Pearsonusesthisinformationforsystemadministrationandtoidentifyproblems,improveservice,detectunauthorizedaccessandfraudulentactivity,preventandrespondtosecurityincidents,appropriatelyscalecomputingresourcesandotherwisesupportanddeliverthissiteanditsservices.
CookiesandRelatedTechnologies
Thissiteusescookiesandsimilartechnologiestopersonalizecontent,measuretrafficpatterns,controlsecurity,trackuseandaccessofinformationonthissite,andprovideinterest-basedmessagesandadvertising.Userscanmanageandblocktheuseofcookiesthroughtheirbrowser.Disablingorblockingcertaincookiesmaylimitthefunctionalityofthissite.
DoNotTrack
ThissitecurrentlydoesnotrespondtoDoNotTracksignals.
Security
Pearsonusesappropriatephysical,administrativeandtechnicalsecuritymeasurestoprotectpersonalinformationfromunauthorizedaccess,useanddisclosure.
Children
Thissiteisnotdirectedtochildrenundertheageof13.Marketing
Pearsonmaysendordirectmarketingcommunicationstousers,providedthat
PearsonwillnotusepersonalinformationcollectedorprocessedasaK-12schoolserviceproviderforthepurposeofdirectedortargetedadvertising.
SuchmarketingisconsistentwithapplicablelawandPearson'slegalobligations.
Pearsonwillnotknowinglydirectorsendmarketingcommunicationstoanindividualwhohasexpressedapreferencenottoreceivemarketing.
Whererequiredbyapplicablelaw,expressorimpliedconsenttomarketingexistsandhasnotbeenwithdrawn.
PearsonmayprovidepersonalinformationtoathirdpartyserviceprovideronarestrictedbasistoprovidemarketingsolelyonbehalfofPearsonoranaffiliateorcustomerforwhomPearsonisaserviceprovider.Marketingpreferencesmaybechangedatanytime.
Correcting/UpdatingPersonalInformation
Ifauser'spersonallyidentifiableinformationchanges(suchasyourpostaladdressoremailaddress),weprovideawaytocorrectorupdatethatuser'spersonaldataprovidedtous.ThiscanbedoneontheAccountpage.Ifausernolongerdesiresourserviceanddesirestodeletehisorheraccount,pleasecontactusatcustomer-service@informit.comandwewillprocessthedeletionofauser'saccount.
Choice/Opt-out
UserscanalwaysmakeaninformedchoiceastowhethertheyshouldproceedwithcertainservicesofferedbyInformIT.Ifyouchoosetoremoveyourselffromourmailinglist(s)simplyvisitthefollowingpageanduncheckanycommunicationyounolongerwanttoreceive:www.informit.com/u.aspx.SaleofPersonalInformation
Pearsondoesnotrentorsellpersonalinformationinexchangeforanypaymentofmoney.
WhilePearsondoesnotsellpersonalinformation,asdefinedinNevadalaw,NevadaresidentsmayemailarequestfornosaleoftheirpersonalinformationtoNevadaDesignatedRequest@pearson.com.
SupplementalPrivacyStatementforCaliforniaResidents
CaliforniaresidentsshouldreadourSupplementalprivacystatementforCaliforniaresidentsinconjunctionwiththisPrivacyNotice.TheSupplementalprivacystatementforCaliforniaresidentsexplainsPearson'scommitmenttocomplywithCalifornialawandappliestopersonalinformationofCaliforniaresidentscollectedinconnectionwiththissiteandtheServices.
SharingandDisclosure
Pearsonmaydisclosepersonalinformation,asfollows:
Asrequiredbylaw.
Withtheconsentoftheindividual(ortheirparent,iftheindividualisaminor)
Inresponsetoasubpoena,courtorderorlegalprocess,totheextentpermittedorrequiredbylaw
Toprotectthesecurityandsafetyofindividuals,data,assetsandsystems,consistentwithapplicablelaw
Inconnectionthesale,jointventureorothertransferofsomeorallofitscompanyorassets,subjecttotheprovisionsofthisPrivacyNotice
Toinvestigateoraddressactualorsuspectedfraudorotherillegalactivities
Toexerciseitslegalrights,includingenforcementoftheTermsofUseforthissiteoranothercontract
ToaffiliatedPearsoncompaniesandothercompaniesandorganizationswhoperformworkforPearsonandareobligatedtoprotecttheprivacyofpersonalinformationconsistentwiththisPrivacyNotice
Toaschool,organization,companyorgovernmentagency,wherePearsoncollectsorprocessesthepersonalinformationinaschoolsettingoronbehalfofsuchorganization,companyorgovernmentagency.
Links
Thiswebsitecontainslinkstoothersites.Pleasebeawarethatwearenotresponsiblefortheprivacypracticesofsuchothersites.WeencourageouruserstobeawarewhentheyleaveoursiteandtoreadtheprivacystatementsofeachandeverywebsitethatcollectsPersonalInformation.Thisprivacystatementappliessolelytoinformationcollectedbythiswebsite.
RequestsandContact
PleasecontactusaboutthisPrivacyNoticeorifyouhaveanyrequestsorquestionsrelatingtotheprivacyofyourpersonalinformation.
ChangestothisPrivacyNotice
WemayrevisethisPrivacyNoticethroughanupdatedposting.Wewillidentifytheeffectivedateoftherevisionintheposting.Often,updatesaremadetoprovidegreaterclarityortocomplywithchangesinregulatoryrequirements.Iftheupdatesinvolvematerialchangestothecollection,protection,useordisclosureofPersonalInformation,Pearsonwillprovidenoticeofthechangethroughaconspicuousnoticeonthissiteorotherappropriateway.Continueduseofthesiteaftertheeffectivedateofapostedrevisionevidencesacceptance.PleasecontactusifyouhavequestionsorconcernsaboutthePrivacyNoticeoranyobjectiontoanyrevisions.
LastUpdate:November17,2020
EmailAddress
books,eBooks,anddigitallearning
ViewYourCart
Join|SignIn
SearchSearch
ViewYourCart
👤SignIn
Join
Store
Business&Management
Certification
CloudComputing&Virtualization
DataDigitalPhotographyEngineering
Graphics&WebDesign
Home&OfficeComputing
InformationTechnology
MobileApplicationDevelopment&Programming
NetworkingOpenSourceOperatingSystems,ServerProgrammingSecurity
SoftwareDevelopment&Management
WebDevelopmentWebServicesFormatsBookseBooksPracticeTestsSoftwareVideoWebEditionsDeals&PromotionsVideoTrainingImprintsAddison-WesleyProfessionalAdobePressCiscoPressFTPressIBMPressMicrosoftPressStoreOraclePressBooksPeachpitPearsonITCertificationQuePublishingSamsPublishingExploreAboutAffiliateProgramAuthorsChapters&ArticlesContactUsDeals&PromotionsPopularTopicsProductRegistrationSpecialOffers&NewsletterVideoTrainingCommunityPressandMediaRelationsProductReviewTeamUserGroupsAboutAffiliatesContactUsFAQLegalNoticeOrderingInformationPearson+PrivacyNoticeDoNotSellMyPersonalInformationPressPromotionsSiteMapWriteforUs
©2022PearsonEducation,Informit.Allrightsreserved.221RiverStreet,Hoboken,NJ07030Pearson