glsl function pointer (or equivalent) - Stack Overflow

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

I am looking for a way to store the functions in an array, either by using function pointers, or by storing the actual equations (e.g. ... Resultsfromthe2022DeveloperSurveyarenowavailable 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 glslfunctionpointer(orequivalent) AskQuestion Asked 6years,6monthsago Modified 1year,5monthsago Viewed 5ktimes 12 Iamattemptingtocalloneofmanyfunctionsbasedonthevalueofavariable.Thevariableissetduringruntime,socodeontheCPUwillnotwork.Usinganif/switchstatementwillbeslowduetothelargenumberofpossibilities.[probablyincorrect] Iamlookingforawaytostorethefunctionsinanarray,eitherbyusingfunctionpointers,orbystoringtheactualequations(e.g.texcoord.x*2)inanarray. Examplepsuedo-code: invec2texcoord; outvec4color; intnumber;//Assignedanumberbetween0and300duringruntime floatfunc1(void){ returntexcoord.x+texcoord.y; } floatfunc2(void){ returntexcoord.x*2; } ... floatfunc299(void){ returntexcoord.y-7; } voidmain(void){ number=; floatoutput=func();//wereaCPU-generatedvalue,andthatseemsunlikelyinyourcase. Theonlygeneralsolutionyouhaveisaswitchstatement.Andquitefrankly,there'snothingwrongwiththat. Imean,you'realreadygoingtoabsolutelymurderyourperformancebydoingthiskindofconditionanyway.Nomatterhowitgetsimplemented,ifdifferentinstancesinthesamewavefrontareexecutingseparatecode,you'rekindascrewedperformance-wise. Nottomention,aswitchstatementdoesnotnecessarilygetslowerbasedonhowmanyconditionsthereare.Howitgetsimplementeddependsentirelyonthehardware.Ifjumptablesareavailable,itcanbedonereasonablyefficiently(ignoringtheaboveperformanceissue,ofcourse). Also,thereisColonelThirtyTwo'sidea,whereyouencodeeachfunction'soperationasadot-productwithaconstantvector.Obviously,thislimitswhatyourvariousfunctionscanactuallyexecute.Butifitworksinyourcase,itworks. 1Ifyouwanttocontestthis,considerthatSPIR-VprovidesananalogtoeveryfeatureofGLSL,nomatterhowredundant,silly,orunnecessary...exceptshadersubroutines. Share Improvethisanswer Follow answeredDec26,2015at0:30 NicolBolasNicolBolas 415k6161goldbadges720720silverbadges912912bronzebadges 1 @jjxtra:Itwouldjustgetclosedasaduplicateofthis. – NicolBolas May9,2018at17:06 Addacomment  |  1 TherearenofunctionpointersinGLSL,butitispossibletodefineastructurewithalistoffunctionnames: structfunctions_list{ intsin; intcos; inttan; intfract; }; constfunctions_listfunctions=functions_list(1,2,3,4); Usingthislistoffunctionnames,itispossibletosimulateacallback: floatcallback(intfunc,floatarg){ if(func==functions.sin) returnsin(arg); elseif(func==functions.cos) returncos(arg); elseif(func==functions.tan) returntan(arg); elseif(func==functions.fract) returnfract(arg); else return0.0; } These"functionpointers"canbeusedtosimulatehigher-orderfunctionsinGLSL. Share Improvethisanswer Follow editedJan25,2021at18:46 NicolBolas 415k6161goldbadges720720silverbadges912912bronzebadges answeredJul2,2019at19:18 AndersonGreenAndersonGreen 27.8k6161goldbadges179179silverbadges312312bronzebadges 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?Browseotherquestionstaggedglslfunction-pointersraytracingoraskyourownquestion. TheOverflowBlog Askedandanswered:theresultsforthe2022Developersurveyarehere! LivingontheEdgewithNetlify(Ep.456) FeaturedonMeta Testingnewtrafficmanagementtool Upcomingcleanupofduplicatevotes AskWizardTestResultsandNextSteps Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Linked 97 Doconditionalstatementsslowdownshaders? 7 SecondorderfunctionsinGLSL? Related 306 What'sthenearestsubstituteforafunctionpointerinJava? 1421 HowdofunctionpointersinCwork? 223 HowtodebugaGLSLshader? 215 Random/noisefunctionsforGLSL 241 Whydofunctionpointerdefinitionsworkwithanynumberofampersands'&'orasterisks'*'? 279 "unpacking"atupletocallamatchingfunctionpointer 7 GLSLfloat/vec3/vec4arraymaxsize=GL_MAX_VERTEX_UNIFORM_VECTORS? 1 OpenGLES-iPhone4-fragmentshadervariablescount 293 Passingcapturinglambdaasfunctionpointer HotNetworkQuestions Isitacceptabletoincludeinformationinaposterthatwasn'tinthepublication? WhatcanIdoifaflightdelaymakesmemissthetransferfromtheairport? RecordsgreaterthanepochtimestampusingonlyLIKEoperator IssoundofUSSEnterprise’sautomaticdooropeningindeedtoiletflushingsound? HowcanIrecovermylosttimeinmycareer? FromwhichepisodeofTOSwasthisgifofSpockpullingclothesoutofadresserdrawertaken? HowcanItellmybossthatmyproductivityislowduetoaconflictwithacoworker,withoutblamingthecoworker? Whatwasthiscompletelydestroyedpiece? ConfusionwithDopplereffectproblem Doescookingfoodinsideapressurecookerandthenleavingitlockedpreserveitsimilartocanning? Whatisthenameofthiscreature? SolvingaSimple'SumandProduct'Problem WhatcountsasawordforthepurposesofSending? Diagnosingfoodparticlesindishwashersprayarm Checkamushroomforest BlockySRTMhillshadeinQGIS Lookingforthenameforanabstractclassthatmodelsfunctionsasobjects Iboughtmyfirstroadbike,andithurtsmybackandhands TheUnaverageables SeparationoftheChurchandStateinHinduism Ifsomesentencehastruth,coulditbecalledsarcasm ArrayaccessisO(1)impliesafixedindexsize,whichimpliesO(1)arraytraversal? Whydoesafemale-femalecouplerbreaktheUSB-Cstandard? Howtomakephoto-realisticlettuce? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-c Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?