GLSL Shaders - Game development - MDN Web Docs

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

Shaders use GLSL (OpenGL Shading Language), a special OpenGL Shading ... Vertex Shaders transform shape positions into 3D drawing coordinates. SkiptomaincontentSkiptosearchSkiptoselectlanguageGamedevelopmentTechniquesforgamedevelopment3DgamesontheWebGLSLShadersArticleActionsEnglish(US)ShadertypesDemoFinalcodeConclusionSeealsoRelatedTopics Introduction Introduction Anatomy Examples APIsforgamedevelopment Canvas CSS Fullscreen Gamepad IndexedDB JavaScript PointerLock SVG TypedArrays WebAudio WebGL WebRTC WebSockets WebVR WebWorkers XMLHttpRequest Techniques Usingasyncscriptsforasm.js Optimizingstartupperformance UsingWebRTCpeer-to-peerdatachannels Efficientanimationforwebgames AudioforWebGames 2Dcollisiondetection Tilesandtilemapsoverview 3DgamesontheWeb 3DgamesontheWeboverview Explainingbasic3Dtheory BuildingupabasicdemowithA-Frame BuildingupabasicdemowithBabylon.js BuildingupabasicdemowithPlayCanvas BuildingupabasicdemowithThree.js WebVR 3Dcollisiondetection BoundingvolumecollisiondetectionwithTHREE.js Implementinggamecontrolmechanisms Controlmechanisms Mobiletouch Desktopwithmouseandkeyboard Desktopwithgamepad Other Tutorials 2DbreakoutgameusingpureJavaScript 2DbreakoutgameusingPhaser 2Dmaze_gamewithdeviceorientation 2DplatformgameusingPhaser Publishinggames Publishinggamesoverview Gamedistribution Gamepromotion Gamemonetization ShadertypesDemoFinalcodeConclusionSeealsoGLSLShadersShadersuseGLSL(OpenGLShadingLanguage),aspecialOpenGLShadingLanguagewithsyntaxsimilartoC.GLSLisexecuteddirectlybythegraphicspipeline.Thereareseveralkindsofshaders,buttwoarecommonlyusedtocreategraphicsontheweb:VertexShadersandFragment(Pixel)Shaders.VertexShaderstransformshapepositionsinto3Ddrawingcoordinates.FragmentShaderscomputetherenderingsofashape'scolorsandotherattributes. GLSLisnotasintuitiveasJavaScript.GLSLisstronglytypedandthereisalotofmathinvolvingvectorsandmatrices.Itcangetverycomplicated—veryquickly.Inthisarticlewewillmakeasimplecodeexamplethatrendersacube.TospeedupthebackgroundcodewewillbeusingtheThree.jsAPI. Asyoumayrememberfromthebasictheoryarticle,avertexisapointina3Dcoordinatesystem.Verticesmay,andusuallydo,haveadditionalproperties.The3Dcoordinatesystemdefinesspaceandtheverticeshelpdefineshapesinthatspace.ShadertypesAshaderisessentiallyafunctionrequiredtodrawsomethingonthescreen.ShadersrunonaGPU(graphicsprocessingunit),whichisoptimizedforsuchoperations.UsingaGPUtodealwithshadersoffloadssomeofthenumbercrunchingfromtheCPU.ThisallowstheCPUtofocusitsprocessingpoweronothertasks,likeexecutingcode.VertexshadersVertexshadersmanipulatecoordinatesina3Dspaceandarecalledoncepervertex.Thepurposeofthevertexshaderistosetupthegl_Positionvariable—thisisaspecial,global,andbuilt-inGLSLvariable.gl_Positionisusedtostorethepositionofthecurrentvertex. Thevoidmain()functionisastandardwayofdefiningthegl_Positionvariable.Everythinginsidevoidmain()willbeexecutedbythevertexshader.Avertexshaderyieldsavariablecontaininghowtoprojectavertex'spositionin3Dspaceontoa2Dscreen.FragmentshadersFragment(ortexture)shadersdefineRGBA(red,green,blue,alpha)colorsforeachpixelbeingprocessed—asinglefragmentshaderiscalledonceperpixel.Thepurposeofthefragmentshaderistosetupthegl_FragColorvariable.gl_FragColorisabuilt-inGLSLvariablelikegl_Position. ThecalculationsresultinavariablecontainingtheinformationabouttheRGBAcolor.DemoLet'sbuildasimpledemotoexplainthoseshadersinaction.BesuretoreadThree.jstutorialfirsttograsptheconceptofthescene,itsobjects,andmaterials. Note:Rememberthatyoudon'thavetouseThree.jsoranyotherlibrarytowriteyourshaders—pureWebGL(WebGraphicsLibrary)ismorethanenough.We'veusedThree.jsheretomakethebackgroundcodealotsimplerandclearertounderstand,soyoucanjustfocusontheshadercode.Three.jsandother3Dlibrariesabstractalotofthingsforyou—ifyouwantedtocreatesuchanexampleinrawWebGL,you'dhavetowritealotofextracodetoactuallymakeitwork. EnvironmentsetupTostartwiththeWebGLshadersyoudon'tneedmuch.Youshould: MakesureyouareusingamodernbrowserwithgoodWebGLsupport,suchasthelatestFirefoxorChrome. Createadirectorytostoreyourexperimentsin. SaveacopyofthelatestminimizedThree.jslibraryinsideyourdirectory. HTMLstructureHere'stheHTMLstructurewewilluse.

MDNGames:Shadersdemo //vertexshader'scodegoeshere //fragmentshader'scodegoeshere Itcontainssomebasicinformationlikethedocument,andsomeCSStosetthewidthandheightofthe<canvas>elementthatThree.jswillinsertonthepagetobethefullsizeoftheviewport.The <scriptid> voidmain(){ gl_Position=projectionMatrix*modelViewMatrix*vec4(position.x+10.0,position.y,position.z+5.0,1.0); } <scriptid> voidmain(){ gl_FragColor=vec4(0.0,0.58,0.86,1.0); } JavaScriptvarWIDTH=window.innerWidth; varHEIGHT=window.innerHeight; varrenderer=newTHREE.WebGLRenderer({antialias:true}); renderer.setSize(WIDTH,HEIGHT); renderer.setClearColor(0xDDDDDD,1); document.body.appendChild(renderer.domElement); varscene=newTHREE.Scene(); varcamera=newTHREE.PerspectiveCamera(70,WIDTH/HEIGHT); camera.position.z=50; scene.add(camera); varboxGeometry=newTHREE.BoxGeometry(10,10,10); varshaderMaterial=newTHREE.ShaderMaterial({ vertexShader:document.getElementById('vertexShader').textContent, fragmentShader:document.getElementById('fragmentShader').textContent }); varcube=newTHREE.Mesh(boxGeometry,shaderMaterial); scene.add(cube); cube.rotation.set(0.4,0.2,0); functionrender(){ requestAnimationFrame(render); renderer.render(scene,camera); } render(); CSSbody{margin:0;padding:0;font-size:0;} canvas{width:100%;height:100%;} ResultConclusionThisarticlehastaughttheverybasicsofshaders.Ourexampledoesn'tdomuchbuttherearemanymorecoolthingsyoucandowithshaders—checkoutsomereallycoolonesonShaderToyforinspirationandtolearnfromtheirsources.Seealso LearningWebGL—forgeneralWebGLknowledge WebGLShadersandGLSLatWebGLFundamentals—forGLSLspecificinformation Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:May14,2022,byMDNcontributors</scriptid></scriptid></canvas>


請為這篇文章評分?