Hello world! - The Book of Shaders
文章推薦指數: 80 %
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).
<
延伸文章資訊
- 1WebGL着色器内置变量gl_PointSize - gl_FragCoord - CSDN博客
gl_FragColor, 片元颜色值, vec4. gl_FragCoord, 片元坐标,单位像素, vec2. gl_PointCoord, 点渲染模式对应点像素坐标, vec2 ...
- 2Using gl_FragColor vs. out vec4 color? - Stack Overflow
Writing to gl_FragColor specifies the fragment color that will be used by the subsequent fixed fu...
- 3varying 傳遞著色資訊
至今為止的範例,片段著色器的gl_FragColor 都是寫死的,然而attribute 只能用在頂點著色器中,若想自行指定顏色資訊,應當如何傳遞給片段著色器? 著色器的設計, ...
- 4GLSL着色器- 游戏开发环境 - MDN Web Docs
这个着色器的作用是设置 gl_FragColor 变量, 也是一个GLSL内置变量: void main() { gl_FragColor = makeCalculationsToHaveCol...
- 5一起幫忙解決難題,拯救IT 人的一天
昨天提到fragment shader 輸出gl_FragColor gl_FragColor // vec4 ... gl_FragColor = vec4(1.0, 1.0, 0.0, 1....