What does (gl_FragCoord.z / gl_FragCoord.w) represent?
文章推薦指數: 80 %
z / gl_FragCoord.w is not the camera-space (or world-space) distance to the camera. Nor is it the camera-space planar distance to the ... 2022DeveloperSurveyisopen!Takesurvey. Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Whatdoes(gl_FragCoord.z/gl_FragCoord.w)represent? AskQuestion Asked 9years,5monthsago Modified 1year,11monthsago Viewed 17ktimes 16 16 Iwantactualworldspacedistance,andIgetthefeelingfromexperimentationthat (gl_FragCoord.z/gl_FragCoord.w) isthedepthinworldspace?ButI'mnottoosure. EDITI'vejustfoundwhereIhadoriginallylocatedthissnippetofcode.Apparentlyitistheactualdepthfromthecamera? openglglsl Share Improvethisquestion Follow editedDec4,2012at20:49 Engineer askedDec4,2012at20:24 EngineerEngineer 7,99077goldbadges6060silverbadges9999bronzebadges 2 I'mnotsurewhatyourquestionisexactly.Areyouaskingwhatgl_FragCoord.z'svalueis?Orwhatgl_FragDepth'svalueshouldbe?Orsimplyhowtogetaworld-spacedepth?Thelatterrequiresexplainingwhatexactlyyoumeanbyworld-spacedepth,since"depth"isusuallydefinedastheplanardistancetothecamera. – NicolBolas Dec4,2012at20:41 1 Asstatedinthequestion,Iwanttheactualdistance,inworldspaceunits,fromthecamera(orit'snearplane,ifthatismoreappropriate). – Engineer Dec4,2012at20:45 Addacomment | 3Answers 3 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 29 Thiswasasked(bythesameperson)andansweredelsewhere.I'mparaphrasingandembellishingtheanswerhere: Asstatedinsection15.2.2oftheOpenGL4.3coreprofilespecification(PDF),gl_FragCoord.wis1/clip.w,whereclip.wistheWcomponentoftheclip-spaceposition(ie:whatyouwrotetogl_Position). gl_FragCoord.zisgeneratedbythefollowingprocess,assumingtheusualtransforms: Camera-spacetoclip-spacetransform,viaprojectionmatrixmultiplicationinthevertexshader.clip.z=(projectionMatrix*cameraPosition).z Transformtonormalizeddevicecoordinates.ndc.z=clip.z/clip.w Transformtowindowcoordinates,usingtheglDepthRangenear/farvalues.win.z=((dfar-dnear)/2)*ndc.z+(dfar+dnear)/2. Now,usingthedefaultdepthrangeofnear=0,far=1,wecandefinewin.zintermsofclip-space:(clip.z/clip.w)/2+0.5.Ifwethendividethisbygl_FragCoord.w,thatistheequivalentofmultiplyingbyclip.w,thusgivingus: (gl_FragCoord.z/gl_FragCoord.w)=clip.z/2+clip.w/2=(clip.z+clip.w)/2 Usingthestandardprojectionmatrix,clip.zrepresentsascaleandoffsetfromcamera-spaceZcomponent.Thescaleandoffsetaredefinedbythecamera'snear/fardepthvalues.clip.wis,againinthestandardprojectionmatrix,justthenegationofthecamera-spaceZ.Therefore,wecanredefineourequationinthoseterms: (gl_FragCoord.z/gl_FragCoord.w)=(A*cam.z+B-cam.z)/2=(C*cam.z+D) WhereAandBrepresenttheoffsetandscalebasedonnear/far,andC=(A-1)/2andD=B/2. Therefore,gl_FragCoord.z/gl_FragCoord.wisnotthecamera-space(orworld-space)distancetothecamera.Norisitthecamera-spaceplanardistancetothecamera.Butitisalineartransformofthecamera-spacedepth.Youcoulduseitasawaytocomparetwodepthvaluestogether,iftheycamefromthesameprojectionmatrixandsoforth. Toactuallycomputethecamera-spaceZ,youneedtoeitherpassthecameranear/farfromyourmatrix(OpenGLalreadygivesyoutherangenear/far)andcomputethoseAandBvaluesfromthem,oryouneedtousetheinverseoftheprojectionmatrix.Alternatively,youcouldjustusetheprojectionmatrixdirectlyyourself,sincefragmentshaderscanusethesameuniformsavailabletovertexshaders.YoucanpicktheAandBtermsdirectlyfromthatmatrix.A=projectionMatrix[2][2],andB=projectionMatrix[3][2]. Share Improvethisanswer Follow editedJun15,2020at0:01 communitywiki 2revsNicolBolas Addacomment | 3 Accordingtothedocs: Availableonlyinthefragmentlanguage,gl_FragDepthisanoutputvariablethat isusedtoestablishthedepthvalueforthecurrentfragment.Ifdepthbuffering isenabledandnoshaderwritestogl_FragDepth,thenthefixedfunctionvalue fordepthwillbeused(thisvalueiscontainedinthezcomponentof gl_FragCoord)otherwise,thevaluewrittentogl_FragDepthisused. So,itlookslikegl_FragDepthshouldjustbegl_FragCoord.zunlessyou'vesetitsomewhereelseinyourshaders. Share Improvethisanswer Follow answeredDec4,2012at20:38 XymostechXymostech 9,39033goldbadges3333silverbadges4444bronzebadges 8 1 Nope,itisn't.That'swhatIoriginallythought.Ijustswappedoutthegl_FragCoord.zinmyequationwithgl_FragDepth(fortheproductionoflinearfog)tocheckyouranswer,andsuddenlymyentiresceneisblackirrespectiveofdistance.WhereaswhenIleaveintheoriginalgl_FragCoord.z,Iseefogaftersomespecifieddistance. – Engineer Dec4,2012at20:42 @NickWiggill:YoucannotarguewiththeOpenGLspecification.Ifyourcodeisproducingthatresult,thenitiseitherduetoabuginyourcodeorabugintheimplementation.That'swhatiswritteninthespec,andthereforethatishowOpenGLbehaves. – NicolBolas Dec4,2012at20:51 1 @NickWiggill:Idon'tunderstandthemathsbehindit?Idon'tunderstandthemathsbehindit?Idon'tneedtogoarounddisprovingnonsense;thespecsayswhatitsays,andthatpageiswrong. – NicolBolas Dec4,2012at20:57 6 @NickWiggill:Yes,peoplepromotingnon-informationasrealanddownvotingrealfactswindsmeup. – NicolBolas Dec4,2012at21:00 1 @EngineerYouaremixingINPUTvariableswithOUTPUTvalues.'gl_FragCoord.z'isavailabletoyouasINPUT.Thisisnottruefor'gl_FragDepth'.ItisanOUTPUTvaluethatshallbefilledbyyou.Ifyoudon'tfillit,specssaythatitwillbefilledautomaticallywith'gl_FragCoord.z'.Youshouldnotuse'gl_FragDepth'asINPUT. – JoãoMonteiro Apr29,2019at3:00 | Show3morecomments 0 As gl_FragCoord.w=1.0/gl_Position.w And(likely)yourprojectionmatrixgetswfrom-z(ifthelastcolumnis0,0,-1,0)then; floatdistanceToCamera=1.0/gl_FragCoord.w; Share Improvethisanswer Follow answeredMay18,2013at14:32 MarcusOPlattsMarcusOPlatts 44744silverbadges99bronzebadges Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedopenglglsloraskyourownquestion. TheOverflowBlog Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444) Thescienceofinterviewingdevelopers FeaturedonMeta AnnouncingthearrivalofValuedAssociate#1214:Dalmarus Improvementstositestatusandincidentcommunication RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser Temporarilypausingthesitesatisfactionsurvey StagingGround:ReviewerMotivation,Scaling,andOpenQuestions Linked 2 AccessingtheDepthBufferfromafragmentshader 0 Reconstructingworldpositionfromlineardepth Related 283 Onceuponatime,when>wasfasterthan<...wait glslgl_fragcoord.zcalculationandsettinggl_fragdepth cascadedshadowmappinglookupdecision depthasdistancetocameraplaneinglsl glslsampler2dshadowandshadow2dclarification glslcomputeworldcoordinatefromeyedepthandscreenposition rangebasedfoginglsl world-spacepositionfromlogarithmicdepthbuffer x-y-distancefromcameratoobjectinvertexshader hotnetworkquestions aquestionaboutcubenuroadracefe provingarecursiveformulaisindeedafunction unabletomountalinuxraidarray howdoeshebrews11:27saymoseswasnotafraid using covidtestrequirementfordubaitransitfromirelandtoindonesia doesgravitationreallyexistattheparticlelevel selectonlyonepointinpolygonusingqgis qgisreadsblankcellsas howdoyougagafish-personwithouttape howcanaverbalreasoningquestionbesolvedwithmathematica meaningofclappingattheendofmass signalprocessinginpythonvsc whydoesbendersay whydoesthex86nothaveaninstructiontoobtainitsinstructionpointer isitdangeroustoconsume30mgofzinc isitillegaltorideadrunkhorse whatmakesaluminumaerospacegrade howtomodelasimpleshoe whatdoestheidiomaticphrase colourina5by5grid whatproblemscoulde6introducewhenusedfordungeonsanddragonsfifthedition whattapeformatdidthenintendofamicomdatarecorderuse morehotquestions questionfeed subscribetorss tosubscribetothisrssfeed lang-c yourprivacy byclicking acceptallcookies customizesettings>
延伸文章資訊
- 1What does (gl_FragCoord.z / gl_FragCoord.w) represent?
z / gl_FragCoord.w is not the camera-space (or world-space) distance to the camera. Nor is it the...
- 2关于GLSL的gl_FragCoord、gl_FragDepth以及深度计算
gl_FragCoord和gl_FragDepth分别是片元着色器的输入和输出变量。 gl_FragCoord是个vec4,四个分量分别对应x, y, z和1/w。其中,x和y是当前片元的窗口 ...
- 3opengl glsl 深度計算 - w3c學習教程
gl_fragcoord和gl_fragdepth分別是片元著色器的輸入和輸出變數。 gl_fragcoord是個vec4,四個分量分別對應x, y, z和1/w。其中,x和y ...
- 4高级GLSL
如果着色器中没有像 gl_FragDepth 变量写入,它就会自动采用 gl_FragCoord.z 的值。 我们自己设置深度值有一个显著缺点,因为只要我们在片段着色器中对 gl_FragDep...
- 5gl_FragCoord.z - OpenGL: Advanced Coding - Khronos Forums
gl_FragCoord is window-relative (screen) coordinates. .xy is pixel units of the center of the fra...