Don't blend a polyline that has crossed lines with itself in webgl

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

I'm drawing two polylines (which are lines in the sample) in webgl with enabled blending. gl.uniform4f(colorUniformLocation, 0, 0, 0, ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. LearnmoreaboutCollectives Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. LearnmoreaboutTeams Don'tblendapolylinethathascrossedlineswithitselfinwebgl AskQuestion Asked 2years,11monthsago Modified 2years,11monthsago Viewed 92times 0 I'mdrawingtwopolylines(whicharelinesinthesample)inwebglwithenabledblending. gl.uniform4f(colorUniformLocation,0,0,0,0.3); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA); gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array([0.2,-1,0.2,1,]),gl.STATIC_DRAW); gl.drawArrays(gl.LINE_STRIP,0,2); gl.bufferData(gl.ARRAY_BUFFER,newFloat32Array([0,-1,0,1,0,-1,0,1]),gl.STATIC_DRAW); gl.drawArrays(gl.LINE_STRIP,0,4); Hereisthecodepensample. Theleftlinearecrossedwithitselfanditseemslikeitblendswithitself,soasresultitbecomesdarker. Iwouldliketheblendtoworkbetweenthosepolylines,butdon'twantapolylinetoblendwithitself.Isthereawaytodoit? webglalphablendingwebgl2 Share Follow askedSep30,2019at13:17 mt_sergmt_serg 7,34944goldbadges2727silverbadges4545bronzebadges Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 1 Onewaywouldbetousethestenciltest.You'dsetwebglsothatthestencilstoresacertainvaluewhenapixelisdrawnandyou'dsetthestenciltestsoitfailsifitseesthatvalue. Firstanexamplethatdraws2setsof2overlappingtriangleswithblendingon.Thepairswillgetdarkerwheretheyoverlap functionmain(){ constm4=twgl.m4; constgl=document .querySelector('canvas') .getContext('webgl'); constvs=` attributevec4position; uniformmat4matrix; voidmain(){ gl_Position=matrix*position; } `; constfs=` precisionmediumpfloat; uniformvec4color; voidmain(){ gl_FragColor=color; } `; //compileshader,linkprogram,lookuplocations constprogramInfo=twgl.createProgramInfo(gl,[vs,fs]); gl.useProgram(programInfo.program); //createabufferandputdatainit constbufferInfo=twgl.createBufferInfoFromArrays(gl,{ position:{ numComponents:2, data:[ -0.5,-0.2, 0.5,-0.2, 0.5,0.2, -0.2,-0.5, -0.2,0.5, 0.2,0.5, ], }, }); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA); //callsgl.bindBuffer,gl.enableVertexAttribArray,gl.vertexAttribPointer twgl.setBuffersAndAttributes(gl,programInfo,bufferInfo); //callsgl.uniform?? twgl.setUniforms(programInfo,{ color:[0.5,0,0,0.5], matrix:m4.identity(), }); //callsgl.drawArraysorgl.drawElements twgl.drawBufferInfo(gl,bufferInfo); twgl.setUniforms(programInfo,{ color:[0,0,0.5,0.5], matrix:m4.rotateZ( m4.translation([-0.1,0.2,0]), Math.PI*1.2), }); twgl.drawBufferInfo(gl,bufferInfo); } main(); Thenthesameexamplewiththestencilteston Firstweneedtoaskforastencilbuffer constgl=someCanvas.getContext('webgl2',{stencil:true}); Thenweturnonthestenciltest gl.enable(gl.STENCIL_TEST); Setupthetestsoitonlydrawsifthestencilbufferiszero gl.stencilFunc( gl.EQUAL,//thetest 0,//referencevalue 0xFF,//mask ); Andsettheoperationsoweincrementthestencilwhenwedrawsotheywillnolongerbezeroandthereforefailthetest gl.stencilOp( gl.KEEP,//whattodoifthestenciltestfails gl.KEEP,//whattodoifthedepthtestfails gl.INCR,//whattodoifbothtestspass ); Betweenthefirstdrawandthesecondweclearthestencilbuffer gl.clear(gl.STENCIL_BUFFER_BIT); Example functionmain(){ constm4=twgl.m4; constgl=document .querySelector('canvas') .getContext('webgl',{stencil:true}); constvs=` attributevec4position; uniformmat4matrix; voidmain(){ gl_Position=matrix*position; } `; constfs=` precisionmediumpfloat; uniformvec4color; voidmain(){ gl_FragColor=color; } `; //compileshader,linkprogram,lookuplocations constprogramInfo=twgl.createProgramInfo(gl,[vs,fs]); gl.useProgram(programInfo.program); //createabufferandputdatainit constbufferInfo=twgl.createBufferInfoFromArrays(gl,{ position:{ numComponents:2, data:[ -0.5,-0.2, 0.5,-0.2, 0.5,0.2, -0.2,-0.5, -0.2,0.5, 0.2,0.5, ], }, }); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE,gl.ONE_MINUS_SRC_ALPHA); gl.enable(gl.STENCIL_TEST); gl.stencilFunc( gl.EQUAL,//thetest 0,//referencevalue 0xFF,//mask ); gl.stencilOp( gl.KEEP,//whattodoifthestenciltestfails gl.KEEP,//whattodoifthedepthtestfails gl.INCR,//whattodoifbothtestspass ); //callsgl.bindBuffer,gl.enableVertexAttribArray,gl.vertexAttribPointer twgl.setBuffersAndAttributes(gl,programInfo,bufferInfo); //callsgl.uniform?? twgl.setUniforms(programInfo,{ color:[0.5,0,0,0.5], matrix:m4.identity(), }); //callsgl.drawArraysorgl.drawElements twgl.drawBufferInfo(gl,bufferInfo); gl.clear(gl.STENCIL_BUFFER_BIT); twgl.setUniforms(programInfo,{ color:[0,0,0.5,0.5], matrix:m4.rotateZ( m4.translation([-0.1,0.2,0]), Math.PI*1.2), }); twgl.drawBufferInfo(gl,bufferInfo); } main(); Anothersolutionyoucouldalsousethedepthtestifyou'redrawing2Dstuff.Thedefaultdepthtestonlydrawsifthedepthisgl.LESSthanthecurrentdepthsojustturningthedepthtestonandsettingadifferentdepthbetweendrawswouldalsoworkifthedepthofthetrianglesisthesame.Youcouldcomputeadifferentdepthvalueforeachthingyoudraw,you'dneedtolookupthebitresolutionofthedepthbuffer.Or,youcouldusegl.polygonOffset gl.enable(gl.DEPTH_TEST); gl.enable(gl.POLYGON_OFFSET_FILL); ...then... for(leti=0;i Share Follow editedOct1,2019at1:57 answeredSep30,2019at16:57 gmangman 94.1k2929goldbadges239239silverbadges355355bronzebadges 1 Thanksyoualotforthisclearandcomprehensiveanswer!Thestencilwayworksgreatforme. – mt_serg Oct1,2019at8:58 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?Browseotherquestionstaggedwebglalphablendingwebgl2oraskyourownquestion. TheOverflowBlog Functionalprogrammingisanidealfitfordevelopingblockchains Environmentson-demand(Ep.479) FeaturedonMeta AnnouncingtheStackOverflowStudentAmbassadorProgram GoogleAnalytics4(GA4)upgrade StagingGroundWorkflow:QuestionLifecycle The[option]tagisbeingburninated CollectivesUpdate:WSO2launches,andGoogleGosunsets Related 18 opengl-blendingwithpreviouscontentsofframebuffer 6 ChangeAlphaBlendModeinWPF? 2 ArtifactswhenblendingtransparentimageswithGDI+ 6 BlendtwocanvasesontoonewithWebGL 2 BlendinginOpenGLESnotworkinglikeIthinkitshould 0 WebGL:Howcanblendeachdrawwiththepreviousframebufferwithcustomblendingmodes? 3 WebGLgl_FragColoralphabehavedifferentlyinChromewithFirefox HotNetworkQuestions Istheword"here"unnecessaryinthissentence:"Hi,BobtheCanadianhere"? Livealongerlife Fasterthanlightinformation EtiquetteforanincorrectPR Componentthatrespondstoamperage Howsafeanddurableiscommercialmeatpackagingwhenexposedtoalkalineandacidicmarinades? Whyisablackribbonhungoveraperson'sportraitwhentheydie? Interviewerkeepsstringingmealong.HowshouldIrespondtotheirlatestresponse? Whataresomewarningsignsthataresearchprojectwillfail? DoIneedpermissionfromcoauthorstopresentapublishedpaperatconference? Istherealawagainstsigningacontracttodosomethingillegal? IsDarkMatterpossibleifthereisdynamicalfriction? HowcanIrecycleabrokentitaniumframe? QGIS:Betterwaytoshowextentofprintcomposermapsinmaincanvas What'sthestorybehindkoboldsbeinglittlelizards? Yetanothersequencewithlettersandaquestionmark Writeaprogramwiththesmallestwidth Whatarethereasonssomethoughtscannotbesimplified,reducedtoasimplersetorphrases? Logical/ScientificExplanationforUmbrakinesis? Wouldalifetimegymmembershipbesubjecttobankruptcyproceedings? IsitappropriatetoapplyforanassistantprofessorjobinthesamedepartmentwhereIjuststartedmypostdoc? CouldCongress"bribe"thePresidenttosignabillbyincludingapresidentialpayraise? Definition:Whatismeantby"bishoppair"inthiscontext? Isitbadpracticetohavea'superadmin'-sotheyeffectivelybypasssecuritychecksinyoursystem? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?