Hello world! - The Book of Shaders

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

Shader Language has a single main function that returns a color at the end. · The final pixel color is assigned to the reserved global variable gl_FragColor . HelloWorld Usuallythe"Helloworld!"exampleisthefirststeptolearninganewlanguage.It'sasimpleone-lineprogramthatoutputsanenthusiasticwelcomingmessageanddeclaresopportunitiesahead. InGPU-landrenderingtextisanovercomplicatedtaskforafirststep,insteadwe'llchooseabrightwelcomingcolortoshoutourenthusiasm! Ifyouarereadingthisbookinabrowserthepreviousblockofcodeisinteractive.Thatmeansyoucanclickandchangeanypartofthecodeyouwanttoexplore.ChangeswillbeupdatedimmediatelythankstotheGPUarchitecturethatcompilesandreplacesshadersonthefly.Giveitatrybychangingthevaluesonline8. Althoughthesesimplelinesofcodedon'tlooklikealot,wecaninfersubstantialknowledgefromthem: ShaderLanguagehasasinglemainfunctionthatreturnsacolorattheend.ThisissimilartoC. Thefinalpixelcolorisassignedtothereservedglobalvariablegl_FragColor. ThisC-flavoredlanguagehasbuiltinvariables(likegl_FragColor),functionsandtypes.Inthiscasewe'vejustbeenintroducedtovec4thatstandsforafourdimensionalvectoroffloatingpointprecision.Laterwewillseemoretypeslikevec3andvec2togetherwiththepopular:float,intandbool. Ifwelookcloselytothevec4typewecaninferthatthefourargumentsrespondtotheRED,GREEN,BLUEandALPHAchannels.Alsowecanseethatthesevaluesarenormalized,whichmeanstheygofrom0.0to1.0.Later,wewilllearnhownormalizingvaluesmakesiteasiertomapvaluesbetweenvariables. AnotherimportantCfeaturewecanseeinthisexampleisthepresenceofpreprocessormacros.Macrosarepartofapre-compilationstep.Withthemitispossibleto#defineglobalvariablesanddosomebasicconditionaloperation(with#ifdefand#endif).Allthemacrocommandsbeginwithahashtag(#).Pre-compilationhappensrightbeforecompilingandcopiesallthecallsto#definesandcheck#ifdef(isdefined)and#ifndef(isnotdefined)conditionals.Inour"helloworld!"exampleabove,weonlyinserttheline2ifGL_ESisdefined,whichmostlyhappenswhenthecodeiscompiledonmobiledevicesandbrowsers. Floattypesarevitalinshaders,sothelevelofprecisioniscrucial.Lowerprecisionmeansfasterrendering,butatthecostofquality.Youcanbepickyandspecifytheprecisionofeachvariablethatusesfloatingpoint.Inthesecondline(precisionmediumpfloat;)wearesettingallfloatstomediumprecision.Butwecanchoosetosetthemtolow(precisionlowpfloat;)orhigh(precisionhighpfloat;). Thelast,andmaybemostimportant,detailisthatGLSLspecsdon’tguaranteethatvariableswillbeautomaticallycasted.Whatdoesthatmean?Manufacturershavedifferentapproachestoaccelerategraphicscardprocessesbuttheyareforcedtoguaranteeminimumspecs.Automaticcastingisnotoneofthem.Inour“helloworld!”examplevec4hasfloatingpointprecisionandforthatitexpectstobeassignedwithfloats.Ifyouwanttomakegoodconsistentcodeandnotspendhoursdebuggingwhitescreens,getusedtoputtingthepoint(.)inyourfloats.Thiskindofcodewillnotalwayswork: voidmain(){ gl_FragColor=vec4(1,0,0,1);//ERROR } Nowthatwe'vedescribedthemostrelevantelementsofour"helloworld!"program,it'stimetoclickonthecodeblockandstartchallengingallthatwe'velearned.Youwillnotethatonerrors,theprogramwillfailtocompile,showingawhitescreen.Therearesomeinterestingthingstotry,forexample: Tryreplacingthefloatswithintegers,yourgraphiccardmayormaynottoleratethisbehavior. Trycommentingoutline8andnotassigninganypixelvaluetothefunction. Trymakingaseparatefunctionthatreturnsaspecificcoloranduseitinsidemain().Asahint,hereisthecodeforafunctionthatreturnsaredcolor: vec4red(){ returnvec4(1.0,0.0,0.0,1.0); } Therearemultiplewaysofconstructingvec4types,trytodiscoverotherways.Thefollowingisoneofthem: vec4color=vec4(vec3(1.0,0.0,1.0),1.0); Althoughthisexampleisn'tveryexciting,itisthemostbasicexample-wearechangingallthepixelsinsidethecanvastothesameexactcolor.Inthefollowingchapterwewillseehowtochangethepixelcolorsbyusingtwotypesofinput:space(theplaceofthepixelonthescreen)andtime(thenumberofsecondssincethepagewasloaded). <>



請為這篇文章評分?