uniforms - The Book of Shaders
文章推薦指數: 80 %
These inputs are called uniform and come in most of the supported types: float ... In the same way GLSL gives us a default output, vec4 gl_FragColor ...
Uniforms
SofarwehaveseenhowtheGPUmanageslargenumbersofparallelthreads,eachoneresponsibleforassigningthecolortoafractionofthetotalimage.Althougheachparallelthreadisblindtotheothers,weneedtobeabletosendsomeinputsfromtheCPUtoallthethreads.Becauseofthearchitectureofthegraphicscardthoseinputsaregoingtobeequal(uniform)toallthethreadsandnecessarilysetasreadonly.Inotherwords,eachthreadreceivesthesamedatawhichitcanreadbutcannotchange.
Theseinputsarecalleduniformandcomeinmostofthesupportedtypes:float,vec2,vec3,vec4,mat2,mat3,mat4,sampler2DandsamplerCube.Uniformsaredefinedwiththecorrespondingtypeatthetopoftheshaderrightafterassigningthedefaultfloatingpointprecision.
#ifdefGL_ES
precisionmediumpfloat;
#endif
uniformvec2u_resolution;//Canvassize(width,height)
uniformvec2u_mouse;//mousepositioninscreenpixels
uniformfloatu_time;//Timeinsecondssinceload
YoucanpicturetheuniformslikelittlebridgesbetweentheCPUandtheGPU.ThenameswillvaryfromimplementationtoimplementationbutinthisseriesofexamplesI’malwayspassing:u_time(timeinsecondssincetheshaderstarted),u_resolution(billboardsizewheretheshaderisbeingdrawn)andu_mouse(mousepositioninsidethebillboardinpixels).I’mfollowingtheconventionofputtingu_beforetheuniformnametobeexplicitaboutthenatureofthisvariablebutyouwillfindallkindsofnamesforuniforms.ForexampleShaderToy.comusesthesameuniformsbutwiththefollowingnames:
uniformvec3iResolution;//viewportresolution(inpixels)
uniformvec4iMouse;//mousepixelcoords.xy:current,zw:click
uniformfloatiTime;//shaderplaybacktime(inseconds)
Enoughtalking,let'sseetheuniformsinaction.Inthefollowingcodeweuseu_time-thenumberofsecondssincetheshaderstartedrunning-togetherwithasinefunctiontoanimatethetransitionoftheamountofredinthebillboard.
AsyoucanseeGLSLhasmoresurprises.TheGPUhashardwareacceleratedangle,trigonometricandexponentialfunctions.Someofthosefunctionsare:sin(),cos(),tan(),asin(),acos(),atan(),pow(),exp(),log(),sqrt(),abs(),sign(),floor(),ceil(),fract(),mod(),min(),max()andclamp().
Nowitistimeagaintoplaywiththeabovecode.
Slowdownthefrequencyuntilthecolorchangebecomesalmostimperceptible.
Speeditupuntilyouseeasinglecolorwithoutflickering.
Playwiththethreechannels(RGB)indifferentfrequenciestogetinterestingpatternsandbehaviors.
gl_FragCoord
InthesamewayGLSLgivesusadefaultoutput,vec4gl_FragColor,italsogivesusadefaultinput,vec4gl_FragCoord,whichholdsthescreencoordinatesofthepixelorscreenfragmentthattheactivethreadisworkingon.Withvec4gl_FragCoord,weknowwhereathreadisworkinginsidethebillboard.Inthiscasewedon'tcallituniformbecauseitwillbedifferentfromthreadtothread,insteadgl_FragCoordiscalledavarying.
Intheabovecodewenormalizethecoordinateofthefragmentbydividingitbythetotalresolutionofthebillboard.Bydoingthisthevalueswillgobetween0.0and1.0,whichmakesiteasytomaptheXandYvaluestotheREDandGREENchannel.
Inshader-landwedon’thavetoomanyresourcesfordebuggingbesidesassigningstrongcolorstovariablesandtryingtomakesenseofthem.YouwilldiscoverthatsometimescodinginGLSLisverysimilartoputtingshipsinsidebottles.Isequallyhard,beautifulandgratifying.
Nowitistimetotryandchallengeourunderstandingofthiscode.
Canyoutellwherethecoordinate(0.0,0.0)isinourcanvas?
Whatabout(1.0,0.0),(0.0,1.0),(0.5,0.5)and(1.0,1.0)?
Canyoufigureouthowtouseu_mouseknowingthatthevaluesareinpixelsandNOTnormalizedvalues?Canyouuseittomovecolorsaround?
Canyouimagineaninterestingwayofchangingthiscolorpatternusingu_timeandu_mousecoordinates?
Afterdoingtheseexercisesyoumightwonderwhereelseyoucantryyournewshader-powers.Inthefollowingchapterwewillseehowtomakeyourownshadertoolsinthree.js,Processing,andopenFrameworks.
<
延伸文章資訊
- 1一起幫忙解決難題,拯救IT 人的一天
GLSL(OpenGL Shading Language Language)是OpenGL 的Shader 語言,它長得有點像C語言, ... uniform type uniform_name...
- 2GLSL Tutorial – Uniform Variables - Lighthouse3d.com
GLSL Tutorial – Uniform Variables ... Uniform variables act as constants, at least for the durati...
- 3Advanced GLSL - LearnOpenGL
OpenGL gives us a tool called uniform buffer objects that allow us to declare a set of global uni...
- 4着色器
GLSL是为图形计算量身定制的,它包含一些针对向量和矩阵操作的有用特性。 着色器的开头总是要声明版本,接着是输入和输出变量、uniform和 main 函数。每个着色器的入口 ...
- 5OpenGL基础- 统一变量Uniform - 知乎专栏
OpenGL基础: Uniform变量-- 即统一变量简单理解就是一个GLSL shader中的全局常量,可以随意在任意shader(vertex shader, geometry shader...