C++ OpenGL mesh rendering - Stack Overflow

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

OpenGL generate triangle mesh - c++ - Stack Overflow 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 C++OpenGLmeshrendering AskQuestion Asked 6years,4monthsago Modified 6years,4monthsago Viewed 13ktimes 7 2 Iknowtherearealotofresourcesaboutthisontheinternetbuttheydidn'tquiteseemtohelpme. WhatIwanttoachieve: Iambakingameshfromdatawhichstorestheverticesinsideavector. (Vector3isasctructcontaingfloatx,y,z) Itstorestrianglesinamap> (thekeyofthemapisthesubmeshandthevectorthetriangles) theuvinsideavector (Vector2isastructcontainingfloatx,y) andacolorvalueinvector (thecolorvalueappliestoverticesliketheuvdoes) NowIwanttowriteacodethatcanreadthatdataanddrawittothescreenwithmaximumperformance WhatIgot: staticvoidrenderMesh(Meshmesh,floatx,floaty,floatz){ if(mesh.triangles.empty())return; if(mesh.vertices.empty())return; if(mesh.uvs.empty())return; glColor3f(1,1,1); typedefstd::map>::iteratorit_type; for(it_typeiterator=mesh.triangles.begin();iterator!=mesh.triangles.end();iterator++){ intsubmesh=iterator->first; if(submeshsecond.size();i+=3){ intt0=iterator->second[i+0]; intt1=iterator->second[i+1]; intt2=iterator->second[i+2]; Vector3v0=mesh.vertices[t0]; Vector3v1=mesh.vertices[t1]; Vector3v2=mesh.vertices[t2]; Colorc0=mesh.vertexColors[t0]; Colorc1=mesh.vertexColors[t1]; Colorc2=mesh.vertexColors[t2]; Vector2u0=mesh.uvs[t0]; Vector2u1=mesh.uvs[t1]; Vector2u2=mesh.uvs[t2]; glBegin(GL_TRIANGLES); glColor4f(c0.r/255.0f,c0.g/255.0f,c0.b/255.0f,c0.a/255.0f);glTexCoord2d(u0.x,u0.y);glVertex3f(v0.x+x,v0.y+y,v0.z+z); glColor4f(c1.r/255.0f,c1.g/255.0f,c1.b/255.0f,c1.a/255.0f);glTexCoord2d(u1.x,u1.y);glVertex3f(v1.x+x,v1.y+y,v1.z+z); glColor4f(c2.r/255.0f,c2.g/255.0f,c2.b/255.0f,c2.a/255.0f);glTexCoord2d(u2.x,u2.y);glVertex3f(v2.x+x,v2.y+y,v2.z+z); glEnd(); glColor3f(1,1,1); } } } Theproblem: IfoundoutthatthewayIrenderisnotthebestwayandthatyoucanachievehigherperformancewithglDrawArrays(Ithinkitwascalled). CouldyouhelpmerewritingmycodetofitwithglDrawArrays,sincewhatIfoundsofarontheinternetdidnothelpmetoomuch. Thanks,andifthereisanymoreinformationneededjustask. c++openglmesh Share Improvethisquestion Follow editedJan23,2016at15:26 Sheldon askedJan23,2016at12:16 SheldonSheldon 11711goldbadge11silverbadge99bronzebadges 2 4 Justasuggestion:theversionofOpenGLyourarelearninghasbeendeprecatedforanumberofyears.Isuggestyouputyourtimeinlearningamoreuptodateversion.Seealso:stackoverflow.com/questions/14300569/opengl-glbegin-glend – RichardCritten Jan23,2016at12:30 IfyoumovefromOpenGLv1.0tov3.5-4.5youwilltransitiontoGLCallsthatworkwithShadersontheGPUasopposedtoworkingontheCPU.OnceyouhavetheframeworkinplacetouseGLSLthenitcanbeveryefficienttocreateaBatchProcess.UsingBatcheswillmaximizetheamountofverticesperrendercallloweringtheamountofCPUtoGPUcallswhichwillalsoreducethebottleneckthatiscausedwhileworkingacrosstheBus.Workingwithmultiplethreadswillhelpwhereaworkerthreadcanpre-calculateandcreatestoredmemorybufferswhiletheotherthreaddoestherendercalls. – FrancisCugler Jan23,2016at13:37 Addacomment  |  1Answer 1 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 3 TheuseoffunctionslikeglBeginandglEndisdeprecated.FunctionslikeglDrawArrayshaveabetterperformance,butslightlymorecomplicatedtouse. TheproblemofglBeginrendertechniquesisyouhavetocommunicateeachvertexonebyoneeachtimeyouwanttodrawsomething.Today,graphiccardsareabletorenderthousandsofverticesveryquickly,butifyougiveitonebyone,therenderwillbecomelaggyregardlessyourgraphiccardperformance. ThemainadvantageofglDrawArraysisyouhavetoinitializeyourarraysonce,andthendrawitwithonecall.Sofirst,youneedtofillatthestartofyourprogramanarrayforeachattribute.Inyourcase:positions,colorsandtexturecoords.Itmustbefloatarrays,somethinglikethis: std::vectorvertices; std::vectorcolors; std::vectortextureCoords; for(inti=0;isecond.size();i+=3){ intt0=iterator->second[i+0]; intt1=iterator->second[i+1]; intt2=iterator->second[i+2]; vertices.push_back(mesh.vertices[t0].x); vertices.push_back(mesh.vertices[t0].y); vertices.push_back(mesh.vertices[t0].z); vertices.push_back(mesh.vertices[t1].x); vertices.push_back(mesh.vertices[t1].y); vertices.push_back(mesh.vertices[t1].z); vertices.push_back(mesh.vertices[t2].x); vertices.push_back(mesh.vertices[t2].y); vertices.push_back(mesh.vertices[t2].z); //[...]Sameforcolorsandtexturecoords. } Then,inanotherfunctionsetonlyfordisplay,youcanusethesearraysinordertodrawit: //Enableeverythingyouneed glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); //Setyourusedarrays glVertexPointer(3,GL_FLOAT,0,vertices.data()); glColorPointer(4,GL_FLOAT,0,colors.data()); glTexCoordPointer(2,GL_FLOAT,0,textureCoords.data()); //Drawyourmesh glDrawArrays(GL_TRIANGLES,0,size);//'size'isthenumberofyourvertices. //Resetinitialstate glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); Ofcourse,you'llhavetoenableotherattributesyouwanttouse,liketextureorblending. NOTE: Ifyouwishtolearnaboutperformance,therearealsootherfunctionsusingindicesinordertoreducethesizeofdataused,likeglDrawElements. TherearealsoothermoreadvancedOpenGLtechniquesthatallowsyoutoincreaseperformancebysavingyourdatadirectlyonthegraphiccardmemory,likeVertexBufferObjects. Share Improvethisanswer Follow editedJun20,2020at9:12 CommunityBot 111silverbadge answeredJan23,2016at12:41 AracthorAracthor 5,52766goldbadges3030silverbadges5656bronzebadges 10 Thanks,goingtotestit."Itmustbefloatarrays"-soIcan'tuseavectorforthecolors? – Sheldon Jan23,2016at12:47 @SheldonTechnicallyyoucan,butyou'llhavetochangesomeparametersinmysample,likesecondargumentofglColorPointer.MostofprogramsusefloatevenforcolorsbecauseitisthefavoritetypeofOpenGLinitself. – Aracthor Jan23,2016at12:50 @Sheldonbecarefulofwhatyoucalla"vertex".Thethirdargumentisthenumberof"points"ofyourmesh,buteachpointhave3spacecoordinates(x,y,z).Soifyougivethesizeofthe"vertices"vectorasparameter,yougivethreetimestoomanyverticesthatyoushould,andglDrawArraysshalllooktoofaronyourarrays. – Aracthor Jan23,2016at13:28 Trytodisplayjustpositionswithouttextureorcolorsforstart,itshouldbeawhitemesh.Andtrytorenderitwithanon-blackandnon-whiteclearcolor,maybeitisthesamecoloratthebackgroundoneandyoudon'tseeit. – Aracthor Jan23,2016at13:35 ThatwasthefirstthingItried.Itdidn'trender. – Sheldon Jan23,2016at13:39  |  Show5morecomments 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?Browseotherquestionstaggedc++openglmeshoraskyourownquestion. TheOverflowBlog Makeyouropen-sourceprojectpublicbeforeyou’reready(Ep.444) Thescienceofinterviewingdevelopers FeaturedonMeta AnnouncingthearrivalofValuedAssociate#1214:Dalmarus Improvementstositestatusandincidentcommunication RetiringOurCommunity-SpecificClosureReasonsforServerFaultandSuperUser Temporarilypausingthesitesatisfactionsurvey StagingGround:ReviewerMotivation,Scaling,andOpenQuestions Linked 16 OpenGLglBegin...glEnd Related 242 HowdoyourenderprimitivesaswireframesinOpenGL? 0 OpenGLopeningMesh(.m)filewithVisualStudio2010 3 HowtouseproperlyVAOandVBOinavoxelengine 1 C++array/vectorwithafloatindex 1 UnorderedmapcontaininganIteratortoaVector-IteratornotDereferencableC++ -1 RenderingOpenGLmeshtoSFMLRenderTexture HotNetworkQuestions Arethereany/manyUSairports(withinstrumentapproaches)stillwithoutRNAVapproaches? Whyishavingbloatedinterfacesanantipattern? WhatproblemscouldE6introducewhenusedforDungeonsandDragonsFifthedition? Whyweremarijuanarestrictionsimplementedinthe1970smoresuccessfulinSouthKoreathanintheUnitedStates? Whoisthewomaninthepostcreditof"DoctorStrangeintheMultiverseofMadness"? IsitallowedtocopycodeundertheUnityReference-OnlyLicense? GN:Howtopassaninstancer'slocalizedtexturecolortoitsinstances? Can'tmultiplywidthin\newcommandforincludegraphics Googlespreadsheets Movingplayerinsideofmovingspaceship? Twoparallelrelaysfordoublecurrent Whatis"aerospacegrade"? HowManyDaysAfterSkimCoatCanIPaint? IsitOKtousemixedDNSservers? AquestionregardingisomorphismincohomologyformodulispaceofstablebundlesoveracompactRiemannsurface Meaningandoriginoftheword"muist" FindthenthFibonaccinumber,wherenisthemthFibonaccinumber AnelegantwaytowritelongequationsinLaTex? Isitaredflagforacompanytohave"unlimitedpaidtimeoff"? ProbleminNewton'sPrincipiamentionedbyV.I.Arnol'd Waystomakeanalienatmospherebreathable,butuncomfortable? Iworkfromhomeasasoftwareengineerandmyjobishappywithmyperformance.ButI'mputtinginlittleeffort.AmIabadpersonoremployee? Wouldn'tMiller'splanetbefriedbyblueshiftedradiation? Whatdoyoucalladesperateattemptunlikelytosucceed? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cpp Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?