How stencil buffer and masking work? - webgl - Stack Overflow

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

Your program works absolute correctly, but you have to tell the getContext function to create a stencil buffer, when the context is created: 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 Howstencilbufferandmaskingwork? AskQuestion Asked 4years,7monthsago Modified 1yearago Viewed 4ktimes 8 3 Iwanttodrawobjectinjustspecificarea.Pleasetakealookthisimageforreference The2triangles(pictureA)beingdrawjustintheareainsidethequad(pictureB),sotheresultwilllookclipped(pictureC). Firstidrawthequadjustinstencilbuffer. gl.stencilOp(gl.KEEP,gl.KEEP,gl.REPLACE); gl.stencilFunc(gl.ALWAYS,1,0xff); gl.stencilMask(0xff); gl.depthMask(false); gl.colorMask(false,false,false,false); drawQuads(); inmyunderstanding,nowthestencilbufferhasvalue1sinthequadarea.Then,drawthetriangles. gl.stencilFunc(gl.EQUAL,1,0xff); gl.stencilMask(0x00); gl.depthMask(true); gl.colorMask(true,true,true,true); drawTriagles(); Iwasexpecttheresultwillbelikeonthepicture(C),butit'snot.WhatIamdoingwrong? Pleasefindthecompletecodeherehttps://jsfiddle.net/z11zhf01/1 webglwebgl2stencil-buffer Share Improvethisquestion Follow editedMay15,2021at10:14 Rabbid76 176k2525goldbadges101101silverbadges145145bronzebadges askedOct18,2017at8:42 janucariajanucaria 19122silverbadges1212bronzebadges Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 12 Yourprogramworksabsolutecorrectly,butyouhavetotellthegetContextfunctiontocreateastencilbuffer,whenthecontextiscreated: gl=glcanvas.getContext("webgl",{stencil:true}); SeeKhronosWebGLSpecification-WebGLContextAttributes: stencil Ifthevalueistrue,thedrawingbufferhasastencilbufferofatleast8bits.Ifthevalueisfalse,nostencilbufferisavailable. SeetheExample: (function(){ vargl; vargProgram; vargVertexAttribLocation; vargColorAttribLocation; vargTriangleVertexBuffer; vargTriangleColorBuffer; vargQuadVertexBuffer; vargQuadColorBuffer; functioninitGL(){ varglcanvas=document.getElementById("glcanvas"); gl=glcanvas.getContext("webgl",{stencil:true}); } functioncreateAndCompileShader(type,source){ varshader=gl.createShader(type); gl.shaderSource(shader,source); gl.compileShader(shader); if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){ thrownewError(gl.getShaderInfoLog(shader)); } returnshader; } functioncreateAndLinkProgram(glVertexShader,glFragmentShader){ varglProgram=gl.createProgram(); gl.attachShader(glProgram,glVertexShader); gl.attachShader(glProgram,glFragmentShader); gl.linkProgram(glProgram); if(!gl.getProgramParameter(glProgram,gl.LINK_STATUS)){ thrownewError("Couldnotinitialiseshaders"); } returnglProgram; } functioninitShaderPrograms(){ vargVertexShader=createAndCompileShader(gl.VERTEX_SHADER,[ "attributevec3a_vertex;", "attributevec4a_color;", "varyingvec4v_color;", "voidmain(void){", "v_color=a_color;", "gl_Position=vec4(a_vertex,1.0);", "}" ].join("\n")); vargFragmentShader=createAndCompileShader(gl.FRAGMENT_SHADER,[ "precisionmediumpfloat;", "varyingvec4v_color;", "voidmain(void){", "gl_FragColor=v_color;", "}" ].join("\n")); gProgram=createAndLinkProgram(gVertexShader,gFragmentShader); } functioninitGLAttribLocations(){ gVertexAttribLocation=gl.getAttribLocation(gProgram,"a_vertex"); gColorAttribLocation=gl.getAttribLocation(gProgram,"a_color"); } functioninitBuffers(){ gTriangleVertexBuffer=gl.createBuffer(); gTriangleColorBuffer=gl.createBuffer(); gQuadVertexBuffer=gl.createBuffer(); gQuadColorBuffer=gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER,gTriangleVertexBuffer); varvertices=newFloat32Array([ 0.0,1.0,0.0, -1.0,-1.0,0.0, 1.0,-1.0,0.0, 0.0,-1.0,0.0, -1.0,1.0,0.0, 1.0,1.0,0.0 ]); gl.bufferData(gl.ARRAY_BUFFER,vertices,gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER,gTriangleColorBuffer); varcolors=newFloat32Array([ 0.0,1.0,0.0,1.0, 0.0,1.0,0.0,1.0, 0.0,1.0,0.0,1.0, 0.0,0.0,1.0,1.0, 0.0,0.0,1.0,1.0, 0.0,0.0,1.0,1.0 ]); gl.bufferData(gl.ARRAY_BUFFER,colors,gl.STATIC_DRAW); gl.bindBuffer(gl.ARRAY_BUFFER,gQuadVertexBuffer); varvertices=newFloat32Array([ -1.0,1.0,0.0, -1.0,-1.0,0.0, 1.0,1.0,0.0, 1.0,-1.0,0.0 ]); for(leti=0,ii=vertices.length;i WebGLnotsupported! Share Improvethisanswer Follow answeredOct18,2017at9:01 Rabbid76Rabbid76 176k2525goldbadges101101silverbadges145145bronzebadges 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?Browseotherquestionstaggedwebglwebgl2stencil-bufferoraskyourownquestion. TheOverflowBlog Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444) Thescienceofinterviewingdevelopers FeaturedonMeta AnnouncingthearrivalofValuedAssociate#1214:Dalmarus Improvementstositestatusandincidentcommunication RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser Temporarilypausingthesitesatisfactionsurvey StagingGround:ReviewerMotivation,Scaling,andOpenQuestions Related 3 LibGDXStencilBufferswhileusingSpriteBatch 0 DirectX-DeferredShadingw/InstancedStencilVolumes 4 PortingOpenGLstencilfunctionalitytoDirectX11 3 howtopassstencilfromaframebuffertoanother 4 HowtodrawconcaveshapeusingStenciltestonMetal 1 Howdovaluesgetdrawntothestencilbufferinthisexample? 1 WhyGL_RASTERIZER_DISCARDdoesnotenablemetowritetostencilbuffer? HotNetworkQuestions Twoparallelrelaysfordoublecurrent Alternativestotannininplantbark Whatmakesaluminumaerospacegrade? Ihaveanarmadaofteleportingskyfortresses.DoIstillneedanavy? HowcanItellwhich3rdpartyflashesarecompatiblewithCanon'sSL3missingpinhotshoemount? Mathematica13.0simplifiestrigonometricintegralwrong Currentlyself-studyingQFTandTheStandardModelbySchwartzandI'mstuckatequation1.5inPart1regardingblackbodyradiation HowManyDaysAfterSkimCoatCanIPaint? WhatproblemscouldE6introducewhenusedforDungeonsandDragonsFifthedition? Whatisthemostecologicallysustainablewaytohandleragscoveredinchaingrease? IsitallowedtocopycodeundertheUnityReference-OnlyLicense? Partitioningalistbasedonacriterionforsublists 'Mapping'thevaluesofalisttovariable Can"LaCorrida"mean"TheBullfight"? GAMmodelwarningmessage:stepfailureinthetaestimation Ecologyoftheenvironmentfortheruffedgrouse Iworkfromhomeasasoftwareengineerandmyjobishappywithmyperformance.ButI'mputtinginlittleeffort.AmIabadpersonoremployee? StarWars:R2D2connectedtomainframe Longestgeometricprogressionofprimes Googlespreadsheets Didmyprofessoractunethicallybypublishingapaperwithafigurefrommythesiswithoutanyacknowledgement? QGISreadsblankcellsas"nan"insteadof"NULL" Audiosplitterwithoutbufferpossible? WhatdoesGandalftheWhitemeanbyhisstrangespeechaboutBoromir? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?