renderer_gl.cpp 225 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458
  1. /*
  2. * Copyright 2011-2016 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "bgfx_p.h"
  6. #if (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)
  7. # include "renderer_gl.h"
  8. # include <bx/timer.h>
  9. # include <bx/uint32_t.h>
  10. # include "hmd_ovr.h"
  11. #if BGFX_CONFIG_PROFILER_REMOTERY
  12. # define BGFX_GPU_PROFILER_BIND() rmt_BindOpenGL()
  13. # define BGFX_GPU_PROFILER_UNBIND() rmt_UnbindOpenGL()
  14. # define BGFX_GPU_PROFILER_BEGIN(_group, _name, _color) rmt_BeginOpenGLSample(_group##_##_name)
  15. # define BGFX_GPU_PROFILER_BEGIN_DYNAMIC(_namestr) rmt_BeginOpenGLSampleDynamic(_namestr)
  16. # define BGFX_GPU_PROFILER_END() rmt_EndOpenGLSample()
  17. #else
  18. # define BGFX_GPU_PROFILER_BIND() BX_NOOP()
  19. # define BGFX_GPU_PROFILER_UNBIND() BX_NOOP()
  20. # define BGFX_GPU_PROFILER_BEGIN(_group, _name, _color) BX_NOOP()
  21. # define BGFX_GPU_PROFILER_BEGIN_DYNAMIC(_namestr) BX_NOOP()
  22. # define BGFX_GPU_PROFILER_END() BX_NOOP()
  23. #endif // BGFX_CONFIG_PROFILER_REMOTERY
  24. namespace bgfx { namespace gl
  25. {
  26. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  27. struct PrimInfo
  28. {
  29. GLenum m_type;
  30. uint32_t m_min;
  31. uint32_t m_div;
  32. uint32_t m_sub;
  33. };
  34. static const PrimInfo s_primInfo[] =
  35. {
  36. { GL_TRIANGLES, 3, 3, 0 },
  37. { GL_TRIANGLE_STRIP, 3, 1, 2 },
  38. { GL_LINES, 2, 2, 0 },
  39. { GL_LINE_STRIP, 2, 1, 1 },
  40. { GL_POINTS, 1, 1, 0 },
  41. };
  42. static const char* s_primName[] =
  43. {
  44. "TriList",
  45. "TriStrip",
  46. "Line",
  47. "LineStrip",
  48. "Point",
  49. };
  50. static const char* s_attribName[] =
  51. {
  52. "a_position",
  53. "a_normal",
  54. "a_tangent",
  55. "a_bitangent",
  56. "a_color0",
  57. "a_color1",
  58. "a_indices",
  59. "a_weight",
  60. "a_texcoord0",
  61. "a_texcoord1",
  62. "a_texcoord2",
  63. "a_texcoord3",
  64. "a_texcoord4",
  65. "a_texcoord5",
  66. "a_texcoord6",
  67. "a_texcoord7",
  68. };
  69. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) );
  70. static const char* s_instanceDataName[] =
  71. {
  72. "i_data0",
  73. "i_data1",
  74. "i_data2",
  75. "i_data3",
  76. "i_data4",
  77. };
  78. BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) );
  79. static const GLenum s_access[] =
  80. {
  81. GL_READ_ONLY,
  82. GL_WRITE_ONLY,
  83. GL_READ_WRITE,
  84. };
  85. BX_STATIC_ASSERT(Access::Count == BX_COUNTOF(s_access) );
  86. static const GLenum s_attribType[] =
  87. {
  88. GL_UNSIGNED_BYTE, // Uint8
  89. GL_UNSIGNED_INT_10_10_10_2, // Uint10
  90. GL_SHORT, // Int16
  91. GL_HALF_FLOAT, // Half
  92. GL_FLOAT, // Float
  93. };
  94. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  95. struct Blend
  96. {
  97. GLenum m_src;
  98. GLenum m_dst;
  99. bool m_factor;
  100. };
  101. static const Blend s_blendFactor[] =
  102. {
  103. { 0, 0, false }, // ignored
  104. { GL_ZERO, GL_ZERO, false }, // ZERO
  105. { GL_ONE, GL_ONE, false }, // ONE
  106. { GL_SRC_COLOR, GL_SRC_COLOR, false }, // SRC_COLOR
  107. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false }, // INV_SRC_COLOR
  108. { GL_SRC_ALPHA, GL_SRC_ALPHA, false }, // SRC_ALPHA
  109. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false }, // INV_SRC_ALPHA
  110. { GL_DST_ALPHA, GL_DST_ALPHA, false }, // DST_ALPHA
  111. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false }, // INV_DST_ALPHA
  112. { GL_DST_COLOR, GL_DST_COLOR, false }, // DST_COLOR
  113. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false }, // INV_DST_COLOR
  114. { GL_SRC_ALPHA_SATURATE, GL_ONE, false }, // SRC_ALPHA_SAT
  115. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true }, // FACTOR
  116. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true }, // INV_FACTOR
  117. };
  118. static const GLenum s_blendEquation[] =
  119. {
  120. GL_FUNC_ADD,
  121. GL_FUNC_SUBTRACT,
  122. GL_FUNC_REVERSE_SUBTRACT,
  123. GL_MIN,
  124. GL_MAX,
  125. };
  126. static const GLenum s_cmpFunc[] =
  127. {
  128. 0, // ignored
  129. GL_LESS,
  130. GL_LEQUAL,
  131. GL_EQUAL,
  132. GL_GEQUAL,
  133. GL_GREATER,
  134. GL_NOTEQUAL,
  135. GL_NEVER,
  136. GL_ALWAYS,
  137. };
  138. static const GLenum s_stencilOp[] =
  139. {
  140. GL_ZERO,
  141. GL_KEEP,
  142. GL_REPLACE,
  143. GL_INCR_WRAP,
  144. GL_INCR,
  145. GL_DECR_WRAP,
  146. GL_DECR,
  147. GL_INVERT,
  148. };
  149. static const GLenum s_stencilFace[] =
  150. {
  151. GL_FRONT_AND_BACK,
  152. GL_FRONT,
  153. GL_BACK,
  154. };
  155. static GLenum s_textureAddress[] =
  156. {
  157. GL_REPEAT,
  158. GL_MIRRORED_REPEAT,
  159. GL_CLAMP_TO_EDGE,
  160. GL_CLAMP_TO_BORDER,
  161. };
  162. static const GLenum s_textureFilterMag[] =
  163. {
  164. GL_LINEAR,
  165. GL_NEAREST,
  166. GL_LINEAR,
  167. };
  168. static const GLenum s_textureFilterMin[][3] =
  169. {
  170. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST },
  171. { GL_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_NEAREST },
  172. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST },
  173. };
  174. struct TextureFormatInfo
  175. {
  176. GLenum m_internalFmt;
  177. GLenum m_internalFmtSrgb;
  178. GLenum m_fmt;
  179. GLenum m_type;
  180. bool m_supported;
  181. };
  182. static TextureFormatInfo s_textureFormat[] =
  183. {
  184. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, false }, // BC1
  185. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, false }, // BC2
  186. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, false }, // BC3
  187. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, false }, // BC4
  188. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, false }, // BC5
  189. { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, false }, // BC6H
  190. { GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, false }, // BC7
  191. { GL_ETC1_RGB8_OES, GL_ZERO, GL_ETC1_RGB8_OES, GL_ZERO, false }, // ETC1
  192. { GL_COMPRESSED_RGB8_ETC2, GL_ZERO, GL_COMPRESSED_RGB8_ETC2, GL_ZERO, false }, // ETC2
  193. { GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_SRGB8_ETC2, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_ZERO, false }, // ETC2A
  194. { GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_ZERO, false }, // ETC2A1
  195. { GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12
  196. { GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14
  197. { GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12A
  198. { GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14A
  199. { GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, false }, // PTC22
  200. { GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, false }, // PTC24
  201. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // Unknown
  202. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // R1
  203. { GL_ALPHA, GL_ZERO, GL_ALPHA, GL_UNSIGNED_BYTE, false }, // A8
  204. { GL_R8, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8
  205. { GL_R8I, GL_ZERO, GL_RED, GL_BYTE, false }, // R8I
  206. { GL_R8UI, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8U
  207. { GL_R8_SNORM, GL_ZERO, GL_RED, GL_BYTE, false }, // R8S
  208. { GL_R16, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16
  209. { GL_R16I, GL_ZERO, GL_RED, GL_SHORT, false }, // R16I
  210. { GL_R16UI, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16U
  211. { GL_R16F, GL_ZERO, GL_RED, GL_HALF_FLOAT, false }, // R16F
  212. { GL_R16_SNORM, GL_ZERO, GL_RED, GL_SHORT, false }, // R16S
  213. { GL_R32I, GL_ZERO, GL_RED, GL_INT, false }, // R32I
  214. { GL_R32UI, GL_ZERO, GL_RED, GL_UNSIGNED_INT, false }, // R32U
  215. { GL_R32F, GL_ZERO, GL_RED, GL_FLOAT, false }, // R32F
  216. { GL_RG8, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8
  217. { GL_RG8I, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8I
  218. { GL_RG8UI, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8U
  219. { GL_RG8_SNORM, GL_ZERO, GL_RG, GL_BYTE, false }, // RG8S
  220. { GL_RG16, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16
  221. { GL_RG16I, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16I
  222. { GL_RG16UI, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16U
  223. { GL_RG16F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG16F
  224. { GL_RG16_SNORM, GL_ZERO, GL_RG, GL_SHORT, false }, // RG16S
  225. { GL_RG32I, GL_ZERO, GL_RG, GL_INT, false }, // RG32I
  226. { GL_RG32UI, GL_ZERO, GL_RG, GL_UNSIGNED_INT, false }, // RG32U
  227. { GL_RG32F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG32F
  228. { GL_RGB8, GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8
  229. { GL_RGB8I, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8I
  230. { GL_RGB8UI, GL_ZERO, GL_RGB, GL_UNSIGNED_BYTE, false }, // RGB8U
  231. { GL_RGB8_SNORM, GL_ZERO, GL_RGB, GL_BYTE, false }, // RGB8S
  232. { GL_RGB9_E5, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, false }, // RGB9E5F
  233. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // BGRA8
  234. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8
  235. { GL_RGBA8I, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8I
  236. { GL_RGBA8UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8U
  237. { GL_RGBA8_SNORM, GL_ZERO, GL_RGBA, GL_BYTE, false }, // RGBA8S
  238. { GL_RGBA16, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16
  239. { GL_RGBA16I, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16I
  240. { GL_RGBA16UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT, false }, // RGBA16U
  241. { GL_RGBA16F, GL_ZERO, GL_RGBA, GL_HALF_FLOAT, false }, // RGBA16F
  242. { GL_RGBA16_SNORM, GL_ZERO, GL_RGBA, GL_SHORT, false }, // RGBA16S
  243. { GL_RGBA32I, GL_ZERO, GL_RGBA, GL_INT, false }, // RGBA32I
  244. { GL_RGBA32UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT, false }, // RGBA32U
  245. { GL_RGBA32F, GL_ZERO, GL_RGBA, GL_FLOAT, false }, // RGBA32F
  246. { GL_RGB565, GL_ZERO, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, false }, // R5G6B5
  247. { GL_RGBA4, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV, false }, // RGBA4
  248. { GL_RGB5_A1, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, false }, // RGB5A1
  249. { GL_RGB10_A2, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false }, // RGB10A2
  250. { GL_R11F_G11F_B10F, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false }, // R11G11B10F
  251. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // UnknownDepth
  252. { GL_DEPTH_COMPONENT16, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // D16
  253. { GL_DEPTH_COMPONENT24, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D24
  254. { GL_DEPTH24_STENCIL8, GL_ZERO, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // D24S8
  255. { GL_DEPTH_COMPONENT32, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D32
  256. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D16F
  257. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D24F
  258. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D32F
  259. { GL_STENCIL_INDEX8, GL_ZERO, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, false }, // D0S8
  260. };
  261. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  262. static bool s_textureFilter[TextureFormat::Count+1];
  263. static GLenum s_rboFormat[] =
  264. {
  265. GL_ZERO, // BC1
  266. GL_ZERO, // BC2
  267. GL_ZERO, // BC3
  268. GL_ZERO, // BC4
  269. GL_ZERO, // BC5
  270. GL_ZERO, // BC6H
  271. GL_ZERO, // BC7
  272. GL_ZERO, // ETC1
  273. GL_ZERO, // ETC2
  274. GL_ZERO, // ETC2A
  275. GL_ZERO, // ETC2A1
  276. GL_ZERO, // PTC12
  277. GL_ZERO, // PTC14
  278. GL_ZERO, // PTC12A
  279. GL_ZERO, // PTC14A
  280. GL_ZERO, // PTC22
  281. GL_ZERO, // PTC24
  282. GL_ZERO, // Unknown
  283. GL_ZERO, // R1
  284. GL_ALPHA, // A8
  285. GL_R8, // R8
  286. GL_R8I, // R8I
  287. GL_R8UI, // R8U
  288. GL_R8_SNORM, // R8S
  289. GL_R16, // R16
  290. GL_R16I, // R16I
  291. GL_R16UI, // R16U
  292. GL_R16F, // R16F
  293. GL_R16_SNORM, // R16S
  294. GL_R32I, // R32I
  295. GL_R32UI, // R32U
  296. GL_R32F, // R32F
  297. GL_RG8, // RG8
  298. GL_RG8I, // RG8I
  299. GL_RG8UI, // RG8U
  300. GL_RG8_SNORM, // RG8S
  301. GL_RG16, // RG16
  302. GL_RG16I, // RG16I
  303. GL_RG16UI, // RG16U
  304. GL_RG16F, // RG16F
  305. GL_RG16_SNORM, // RG16S
  306. GL_RG32I, // RG32I
  307. GL_RG32UI, // RG32U
  308. GL_RG32F, // RG32F
  309. GL_RGB8, // RGB8
  310. GL_RGB8I, // RGB8I
  311. GL_RGB8UI, // RGB8UI
  312. GL_RGB8_SNORM, // RGB8S
  313. GL_RGB9_E5, // RGB9E5F
  314. GL_RGBA8, // BGRA8
  315. GL_RGBA8, // RGBA8
  316. GL_RGBA8I, // RGBA8I
  317. GL_RGBA8UI, // RGBA8UI
  318. GL_RGBA8_SNORM, // RGBA8S
  319. GL_RGBA16, // RGBA16
  320. GL_RGBA16I, // RGBA16I
  321. GL_RGBA16UI, // RGBA16U
  322. GL_RGBA16F, // RGBA16F
  323. GL_RGBA16_SNORM, // RGBA16S
  324. GL_RGBA32I, // RGBA32I
  325. GL_RGBA32UI, // RGBA32U
  326. GL_RGBA32F, // RGBA32F
  327. GL_RGB565, // R5G6B5
  328. GL_RGBA4, // RGBA4
  329. GL_RGB5_A1, // RGB5A1
  330. GL_RGB10_A2, // RGB10A2
  331. GL_R11F_G11F_B10F, // R11G11B10F
  332. GL_ZERO, // UnknownDepth
  333. GL_DEPTH_COMPONENT16, // D16
  334. GL_DEPTH_COMPONENT24, // D24
  335. GL_DEPTH24_STENCIL8, // D24S8
  336. GL_DEPTH_COMPONENT32, // D32
  337. GL_DEPTH_COMPONENT32F, // D16F
  338. GL_DEPTH_COMPONENT32F, // D24F
  339. GL_DEPTH_COMPONENT32F, // D32F
  340. GL_STENCIL_INDEX8, // D0S8
  341. };
  342. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_rboFormat) );
  343. static GLenum s_imageFormat[] =
  344. {
  345. GL_ZERO, // BC1
  346. GL_ZERO, // BC2
  347. GL_ZERO, // BC3
  348. GL_ZERO, // BC4
  349. GL_ZERO, // BC5
  350. GL_ZERO, // BC6H
  351. GL_ZERO, // BC7
  352. GL_ZERO, // ETC1
  353. GL_ZERO, // ETC2
  354. GL_ZERO, // ETC2A
  355. GL_ZERO, // ETC2A1
  356. GL_ZERO, // PTC12
  357. GL_ZERO, // PTC14
  358. GL_ZERO, // PTC12A
  359. GL_ZERO, // PTC14A
  360. GL_ZERO, // PTC22
  361. GL_ZERO, // PTC24
  362. GL_ZERO, // Unknown
  363. GL_ZERO, // R1
  364. GL_ALPHA, // A8
  365. GL_R8, // R8
  366. GL_R8I, // R8I
  367. GL_R8UI, // R8UI
  368. GL_R8_SNORM, // R8S
  369. GL_R16, // R16
  370. GL_R16I, // R16I
  371. GL_R16UI, // R16U
  372. GL_R16F, // R16F
  373. GL_R16_SNORM, // R16S
  374. GL_R32I, // R32I
  375. GL_R32UI, // R32U
  376. GL_R32F, // R32F
  377. GL_RG8, // RG8
  378. GL_RG8I, // RG8I
  379. GL_RG8UI, // RG8U
  380. GL_RG8_SNORM, // RG8S
  381. GL_RG16, // RG16
  382. GL_RG16I, // RG16I
  383. GL_RG16UI, // RG16U
  384. GL_RG16F, // RG16F
  385. GL_RG16_SNORM, // RG16S
  386. GL_RG32I, // RG32I
  387. GL_RG32UI, // RG32U
  388. GL_RG32F, // RG32F
  389. GL_RGB8, // RGB8
  390. GL_RGB8I, // RGB8I
  391. GL_RGB8UI, // RGB8UI
  392. GL_RGB8_SNORM, // RGB8S
  393. GL_RGB9_E5, // RGB9E5F
  394. GL_RGBA8, // BGRA8
  395. GL_RGBA8, // RGBA8
  396. GL_RGBA8I, // RGBA8I
  397. GL_RGBA8UI, // RGBA8UI
  398. GL_RGBA8_SNORM, // RGBA8S
  399. GL_RGBA16, // RGBA16
  400. GL_RGBA16I, // RGBA16I
  401. GL_RGBA16UI, // RGBA16U
  402. GL_RGBA16F, // RGBA16F
  403. GL_RGBA16_SNORM, // RGBA16S
  404. GL_RGBA32I, // RGBA32I
  405. GL_RGBA32UI, // RGBA32U
  406. GL_RGBA32F, // RGBA32F
  407. GL_RGB565, // R5G6B5
  408. GL_RGBA4, // RGBA4
  409. GL_RGB5_A1, // RGB5A1
  410. GL_RGB10_A2, // RGB10A2
  411. GL_R11F_G11F_B10F, // R11G11B10F
  412. GL_ZERO, // UnknownDepth
  413. GL_ZERO, // D16
  414. GL_ZERO, // D24
  415. GL_ZERO, // D24S8
  416. GL_ZERO, // D32
  417. GL_ZERO, // D16F
  418. GL_ZERO, // D24F
  419. GL_ZERO, // D32F
  420. GL_ZERO, // D0S8
  421. };
  422. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_imageFormat) );
  423. struct Extension
  424. {
  425. enum Enum
  426. {
  427. AMD_conservative_depth,
  428. AMD_multi_draw_indirect,
  429. ANGLE_depth_texture,
  430. ANGLE_framebuffer_blit,
  431. ANGLE_framebuffer_multisample,
  432. ANGLE_instanced_arrays,
  433. ANGLE_texture_compression_dxt1,
  434. ANGLE_texture_compression_dxt3,
  435. ANGLE_texture_compression_dxt5,
  436. ANGLE_timer_query,
  437. ANGLE_translated_shader_source,
  438. APPLE_texture_format_BGRA8888,
  439. APPLE_texture_max_level,
  440. ARB_clip_control,
  441. ARB_compute_shader,
  442. ARB_conservative_depth,
  443. ARB_copy_image,
  444. ARB_debug_label,
  445. ARB_debug_output,
  446. ARB_depth_buffer_float,
  447. ARB_depth_clamp,
  448. ARB_draw_buffers_blend,
  449. ARB_draw_indirect,
  450. ARB_draw_instanced,
  451. ARB_ES3_compatibility,
  452. ARB_framebuffer_object,
  453. ARB_framebuffer_sRGB,
  454. ARB_get_program_binary,
  455. ARB_half_float_pixel,
  456. ARB_half_float_vertex,
  457. ARB_instanced_arrays,
  458. ARB_internalformat_query,
  459. ARB_internalformat_query2,
  460. ARB_invalidate_subdata,
  461. ARB_map_buffer_range,
  462. ARB_multi_draw_indirect,
  463. ARB_multisample,
  464. ARB_occlusion_query,
  465. ARB_occlusion_query2,
  466. ARB_program_interface_query,
  467. ARB_sampler_objects,
  468. ARB_seamless_cube_map,
  469. ARB_shader_bit_encoding,
  470. ARB_shader_image_load_store,
  471. ARB_shader_storage_buffer_object,
  472. ARB_shader_texture_lod,
  473. ARB_texture_compression_bptc,
  474. ARB_texture_compression_rgtc,
  475. ARB_texture_cube_map_array,
  476. ARB_texture_float,
  477. ARB_texture_multisample,
  478. ARB_texture_rg,
  479. ARB_texture_rgb10_a2ui,
  480. ARB_texture_stencil8,
  481. ARB_texture_storage,
  482. ARB_texture_swizzle,
  483. ARB_timer_query,
  484. ARB_uniform_buffer_object,
  485. ARB_vertex_array_object,
  486. ARB_vertex_type_2_10_10_10_rev,
  487. ATI_meminfo,
  488. CHROMIUM_color_buffer_float_rgb,
  489. CHROMIUM_color_buffer_float_rgba,
  490. CHROMIUM_depth_texture,
  491. CHROMIUM_framebuffer_multisample,
  492. CHROMIUM_texture_compression_dxt3,
  493. CHROMIUM_texture_compression_dxt5,
  494. EXT_bgra,
  495. EXT_blend_color,
  496. EXT_blend_minmax,
  497. EXT_blend_subtract,
  498. EXT_color_buffer_half_float,
  499. EXT_color_buffer_float,
  500. EXT_copy_image,
  501. EXT_compressed_ETC1_RGB8_sub_texture,
  502. EXT_debug_label,
  503. EXT_debug_marker,
  504. EXT_debug_tool,
  505. EXT_discard_framebuffer,
  506. EXT_disjoint_timer_query,
  507. EXT_draw_buffers,
  508. EXT_draw_instanced,
  509. EXT_instanced_arrays,
  510. EXT_frag_depth,
  511. EXT_framebuffer_blit,
  512. EXT_framebuffer_object,
  513. EXT_framebuffer_sRGB,
  514. EXT_gpu_shader4,
  515. EXT_multi_draw_indirect,
  516. EXT_occlusion_query_boolean,
  517. EXT_packed_float,
  518. EXT_read_format_bgra,
  519. EXT_shader_image_load_store,
  520. EXT_shader_texture_lod,
  521. EXT_shadow_samplers,
  522. EXT_sRGB_write_control,
  523. EXT_texture_array,
  524. EXT_texture_compression_dxt1,
  525. EXT_texture_compression_latc,
  526. EXT_texture_compression_rgtc,
  527. EXT_texture_compression_s3tc,
  528. EXT_texture_cube_map_array,
  529. EXT_texture_filter_anisotropic,
  530. EXT_texture_format_BGRA8888,
  531. EXT_texture_rg,
  532. EXT_texture_shared_exponent,
  533. EXT_texture_snorm,
  534. EXT_texture_sRGB,
  535. EXT_texture_storage,
  536. EXT_texture_swizzle,
  537. EXT_texture_type_2_10_10_10_REV,
  538. EXT_timer_query,
  539. EXT_unpack_subimage,
  540. GOOGLE_depth_texture,
  541. GREMEDY_string_marker,
  542. GREMEDY_frame_terminator,
  543. IMG_multisampled_render_to_texture,
  544. IMG_read_format,
  545. IMG_shader_binary,
  546. IMG_texture_compression_pvrtc,
  547. IMG_texture_compression_pvrtc2,
  548. IMG_texture_format_BGRA8888,
  549. INTEL_fragment_shader_ordering,
  550. KHR_debug,
  551. KHR_no_error,
  552. MOZ_WEBGL_compressed_texture_s3tc,
  553. MOZ_WEBGL_depth_texture,
  554. NV_conservative_raster,
  555. NV_copy_image,
  556. NV_draw_buffers,
  557. NV_occlusion_query,
  558. NV_texture_border_clamp,
  559. NVX_gpu_memory_info,
  560. OES_copy_image,
  561. OES_compressed_ETC1_RGB8_texture,
  562. OES_depth24,
  563. OES_depth32,
  564. OES_depth_texture,
  565. OES_element_index_uint,
  566. OES_fragment_precision_high,
  567. OES_get_program_binary,
  568. OES_required_internalformat,
  569. OES_packed_depth_stencil,
  570. OES_read_format,
  571. OES_rgb8_rgba8,
  572. OES_standard_derivatives,
  573. OES_texture_3D,
  574. OES_texture_float,
  575. OES_texture_float_linear,
  576. OES_texture_npot,
  577. OES_texture_half_float,
  578. OES_texture_half_float_linear,
  579. OES_texture_stencil8,
  580. OES_texture_storage_multisample_2d_array,
  581. OES_vertex_array_object,
  582. OES_vertex_half_float,
  583. OES_vertex_type_10_10_10_2,
  584. WEBGL_color_buffer_float,
  585. WEBGL_compressed_texture_etc1,
  586. WEBGL_compressed_texture_s3tc,
  587. WEBGL_compressed_texture_pvrtc,
  588. WEBGL_depth_texture,
  589. WEBGL_draw_buffers,
  590. WEBKIT_EXT_texture_filter_anisotropic,
  591. WEBKIT_WEBGL_compressed_texture_s3tc,
  592. WEBKIT_WEBGL_depth_texture,
  593. Count
  594. };
  595. const char* m_name;
  596. bool m_supported;
  597. bool m_initialize;
  598. };
  599. // Extension registry
  600. //
  601. // ANGLE:
  602. // https://github.com/google/angle/tree/master/extensions
  603. //
  604. // CHROMIUM:
  605. // https://chromium.googlesource.com/chromium/src.git/+/refs/heads/git-svn/gpu/GLES2/extensions/CHROMIUM
  606. //
  607. // EGL:
  608. // https://www.khronos.org/registry/egl/extensions/
  609. //
  610. // GL:
  611. // https://www.opengl.org/registry/
  612. //
  613. // GLES:
  614. // https://www.khronos.org/registry/gles/extensions/
  615. //
  616. // WEBGL:
  617. // https://www.khronos.org/registry/webgl/extensions/
  618. //
  619. static Extension s_extension[] =
  620. {
  621. { "AMD_conservative_depth", false, true },
  622. { "AMD_multi_draw_indirect", false, true },
  623. { "ANGLE_depth_texture", false, true },
  624. { "ANGLE_framebuffer_blit", false, true },
  625. { "ANGLE_framebuffer_multisample", false, false },
  626. { "ANGLE_instanced_arrays", false, true },
  627. { "ANGLE_texture_compression_dxt1", false, true },
  628. { "ANGLE_texture_compression_dxt3", false, true },
  629. { "ANGLE_texture_compression_dxt5", false, true },
  630. { "ANGLE_timer_query", false, true },
  631. { "ANGLE_translated_shader_source", false, true },
  632. { "APPLE_texture_format_BGRA8888", false, true },
  633. { "APPLE_texture_max_level", false, true },
  634. { "ARB_clip_control", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  635. { "ARB_compute_shader", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  636. { "ARB_conservative_depth", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  637. { "ARB_copy_image", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  638. { "ARB_debug_label", false, true },
  639. { "ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  640. { "ARB_depth_buffer_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  641. { "ARB_depth_clamp", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  642. { "ARB_draw_buffers_blend", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  643. { "ARB_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  644. { "ARB_draw_instanced", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  645. { "ARB_ES3_compatibility", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  646. { "ARB_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  647. { "ARB_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  648. { "ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  649. { "ARB_half_float_pixel", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  650. { "ARB_half_float_vertex", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  651. { "ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  652. { "ARB_internalformat_query", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  653. { "ARB_internalformat_query2", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  654. { "ARB_invalidate_subdata", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  655. { "ARB_map_buffer_range", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  656. { "ARB_multi_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  657. { "ARB_multisample", false, true },
  658. { "ARB_occlusion_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  659. { "ARB_occlusion_query2", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  660. { "ARB_program_interface_query", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  661. { "ARB_sampler_objects", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  662. { "ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  663. { "ARB_shader_bit_encoding", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  664. { "ARB_shader_image_load_store", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  665. { "ARB_shader_storage_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  666. { "ARB_shader_texture_lod", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  667. { "ARB_texture_compression_bptc", BGFX_CONFIG_RENDERER_OPENGL >= 44, true },
  668. { "ARB_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  669. { "ARB_texture_cube_map_array", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  670. { "ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  671. { "ARB_texture_multisample", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  672. { "ARB_texture_rg", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  673. { "ARB_texture_rgb10_a2ui", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  674. { "ARB_texture_stencil8", false, true },
  675. { "ARB_texture_storage", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  676. { "ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  677. { "ARB_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  678. { "ARB_uniform_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  679. { "ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  680. { "ARB_vertex_type_2_10_10_10_rev", false, true },
  681. { "ATI_meminfo", false, true },
  682. { "CHROMIUM_color_buffer_float_rgb", false, true },
  683. { "CHROMIUM_color_buffer_float_rgba", false, true },
  684. { "CHROMIUM_depth_texture", false, true },
  685. { "CHROMIUM_framebuffer_multisample", false, true },
  686. { "CHROMIUM_texture_compression_dxt3", false, true },
  687. { "CHROMIUM_texture_compression_dxt5", false, true },
  688. { "EXT_bgra", false, true },
  689. { "EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  690. { "EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  691. { "EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  692. { "EXT_color_buffer_half_float", false, true }, // GLES2 extension.
  693. { "EXT_color_buffer_float", false, true }, // GLES2 extension.
  694. { "EXT_copy_image", false, true }, // GLES2 extension.
  695. { "EXT_compressed_ETC1_RGB8_sub_texture", false, true }, // GLES2 extension.
  696. { "EXT_debug_label", false, true },
  697. { "EXT_debug_marker", false, true },
  698. { "EXT_debug_tool", false, true }, // RenderDoc extension.
  699. { "EXT_discard_framebuffer", false, true }, // GLES2 extension.
  700. { "EXT_disjoint_timer_query", false, true }, // GLES2 extension.
  701. { "EXT_draw_buffers", false, true }, // GLES2 extension.
  702. { "EXT_draw_instanced", false, true }, // GLES2 extension.
  703. { "EXT_instanced_arrays", false, true }, // GLES2 extension.
  704. { "EXT_frag_depth", false, true }, // GLES2 extension.
  705. { "EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  706. { "EXT_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  707. { "EXT_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  708. { "EXT_gpu_shader4", false, true },
  709. { "EXT_multi_draw_indirect", false, true }, // GLES3.1 extension.
  710. { "EXT_occlusion_query_boolean", false, true }, // GLES2 extension.
  711. { "EXT_packed_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  712. { "EXT_read_format_bgra", false, true },
  713. { "EXT_shader_image_load_store", false, true },
  714. { "EXT_shader_texture_lod", false, true }, // GLES2 extension.
  715. { "EXT_shadow_samplers", false, true },
  716. { "EXT_sRGB_write_control", false, true }, // GLES2 extension.
  717. { "EXT_texture_array", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  718. { "EXT_texture_compression_dxt1", false, true },
  719. { "EXT_texture_compression_latc", false, true },
  720. { "EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  721. { "EXT_texture_compression_s3tc", false, true },
  722. { "EXT_texture_cube_map_array", false, true }, // GLES3.1 extension.
  723. { "EXT_texture_filter_anisotropic", false, true },
  724. { "EXT_texture_format_BGRA8888", false, true },
  725. { "EXT_texture_rg", false, true }, // GLES2 extension.
  726. { "EXT_texture_shared_exponent", false, true },
  727. { "EXT_texture_snorm", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  728. { "EXT_texture_sRGB", false, true },
  729. { "EXT_texture_storage", false, true },
  730. { "EXT_texture_swizzle", false, true },
  731. { "EXT_texture_type_2_10_10_10_REV", false, true },
  732. { "EXT_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  733. { "EXT_unpack_subimage", false, true },
  734. { "GOOGLE_depth_texture", false, true },
  735. { "GREMEDY_string_marker", false, true },
  736. { "GREMEDY_frame_terminator", false, true },
  737. { "IMG_multisampled_render_to_texture", false, true },
  738. { "IMG_read_format", false, true },
  739. { "IMG_shader_binary", false, true },
  740. { "IMG_texture_compression_pvrtc", false, true },
  741. { "IMG_texture_compression_pvrtc2", false, true },
  742. { "IMG_texture_format_BGRA8888", false, true },
  743. { "INTEL_fragment_shader_ordering", false, true },
  744. { "KHR_debug", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  745. { "KHR_no_error", false, true },
  746. { "MOZ_WEBGL_compressed_texture_s3tc", false, true },
  747. { "MOZ_WEBGL_depth_texture", false, true },
  748. { "NV_conservative_raster", false, true },
  749. { "NV_copy_image", false, true },
  750. { "NV_draw_buffers", false, true }, // GLES2 extension.
  751. { "NV_occlusion_query", false, true },
  752. { "NV_texture_border_clamp", false, true }, // GLES2 extension.
  753. { "NVX_gpu_memory_info", false, true },
  754. { "OES_copy_image", false, true },
  755. { "OES_compressed_ETC1_RGB8_texture", false, true },
  756. { "OES_depth24", false, true },
  757. { "OES_depth32", false, true },
  758. { "OES_depth_texture", false, true },
  759. { "OES_element_index_uint", false, true },
  760. { "OES_fragment_precision_high", false, true },
  761. { "OES_get_program_binary", false, true },
  762. { "OES_required_internalformat", false, true },
  763. { "OES_packed_depth_stencil", false, true },
  764. { "OES_read_format", false, true },
  765. { "OES_rgb8_rgba8", false, true },
  766. { "OES_standard_derivatives", false, true },
  767. { "OES_texture_3D", false, true },
  768. { "OES_texture_float", false, true },
  769. { "OES_texture_float_linear", false, true },
  770. { "OES_texture_npot", false, true },
  771. { "OES_texture_half_float", false, true },
  772. { "OES_texture_half_float_linear", false, true },
  773. { "OES_texture_stencil8", false, true },
  774. { "OES_texture_storage_multisample_2d_array", false, true },
  775. { "OES_vertex_array_object", false, !BX_PLATFORM_IOS },
  776. { "OES_vertex_half_float", false, true },
  777. { "OES_vertex_type_10_10_10_2", false, true },
  778. { "WEBGL_color_buffer_float", false, true },
  779. { "WEBGL_compressed_texture_etc1", false, true },
  780. { "WEBGL_compressed_texture_s3tc", false, true },
  781. { "WEBGL_compressed_texture_pvrtc", false, true },
  782. { "WEBGL_depth_texture", false, true },
  783. { "WEBGL_draw_buffers", false, true },
  784. { "WEBKIT_EXT_texture_filter_anisotropic", false, true },
  785. { "WEBKIT_WEBGL_compressed_texture_s3tc", false, true },
  786. { "WEBKIT_WEBGL_depth_texture", false, true },
  787. };
  788. BX_STATIC_ASSERT(Extension::Count == BX_COUNTOF(s_extension) );
  789. static const char* s_ARB_shader_texture_lod[] =
  790. {
  791. "texture2DLod",
  792. "texture2DProjLod",
  793. "texture3DLod",
  794. "texture3DProjLod",
  795. "textureCubeLod",
  796. "shadow2DLod",
  797. "shadow2DProjLod",
  798. NULL
  799. // "texture1DLod",
  800. // "texture1DProjLod",
  801. // "shadow1DLod",
  802. // "shadow1DProjLod",
  803. };
  804. static const char* s_EXT_shader_texture_lod[] =
  805. {
  806. "texture2DLod",
  807. "texture2DProjLod",
  808. "textureCubeLod",
  809. NULL
  810. // "texture2DGrad",
  811. // "texture2DProjGrad",
  812. // "textureCubeGrad",
  813. };
  814. static const char* s_EXT_shadow_samplers[] =
  815. {
  816. "shadow2D",
  817. "shadow2DProj",
  818. NULL
  819. };
  820. static const char* s_OES_standard_derivatives[] =
  821. {
  822. "dFdx",
  823. "dFdy",
  824. "fwidth",
  825. NULL
  826. };
  827. static const char* s_OES_texture_3D[] =
  828. {
  829. "texture3D",
  830. "texture3DProj",
  831. "texture3DLod",
  832. "texture3DProjLod",
  833. NULL
  834. };
  835. static const char* s_uisamplers[] =
  836. {
  837. "isampler2D",
  838. "usampler2D",
  839. "isampler3D",
  840. "usampler3D",
  841. "isamplerCube",
  842. "usamplerCube",
  843. NULL
  844. };
  845. static const char* s_texelFetch[] =
  846. {
  847. "texelFetch",
  848. "texelFetchOffset",
  849. NULL
  850. };
  851. static const char* s_textureArray[] =
  852. {
  853. "sampler2DArray",
  854. "sampler2DMSArray",
  855. "samplerCubeArray",
  856. "sampler2DArrayShadow",
  857. NULL
  858. };
  859. static const char* s_ARB_texture_multisample[] =
  860. {
  861. "sampler2DMS",
  862. "isampler2DMS",
  863. "usampler2DMS",
  864. NULL
  865. };
  866. static const char* s_ARB_gpu_shader5[] =
  867. {
  868. "bitfieldReverse",
  869. "floatBitsToInt",
  870. "floatBitsToUint",
  871. "intBitsToFloat",
  872. "uintBitsToFloat",
  873. NULL
  874. };
  875. static const char* s_ARB_shading_language_packing[] =
  876. {
  877. "packHalf2x16",
  878. "unpackHalf2x16",
  879. NULL
  880. };
  881. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  882. {
  883. }
  884. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  885. {
  886. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  887. }
  888. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  889. {
  890. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  891. }
  892. static void GL_APIENTRY stubFrameTerminatorGREMEDY()
  893. {
  894. }
  895. static void GL_APIENTRY stubInsertEventMarker(GLsizei /*_length*/, const char* /*_marker*/)
  896. {
  897. }
  898. static void GL_APIENTRY stubInsertEventMarkerGREMEDY(GLsizei _length, const char* _marker)
  899. {
  900. // If <marker> is a null-terminated string then <length> should not
  901. // include the terminator.
  902. //
  903. // If <length> is 0 then <marker> is assumed to be null-terminated.
  904. uint32_t size = (0 == _length ? (uint32_t)strlen(_marker) : _length) + 1;
  905. size *= sizeof(wchar_t);
  906. wchar_t* name = (wchar_t*)alloca(size);
  907. mbstowcs(name, _marker, size-2);
  908. GL_CHECK(glStringMarkerGREMEDY(_length, _marker) );
  909. }
  910. static void GL_APIENTRY stubObjectLabel(GLenum /*_identifier*/, GLuint /*_name*/, GLsizei /*_length*/, const char* /*_label*/)
  911. {
  912. }
  913. static void GL_APIENTRY stubInvalidateFramebuffer(GLenum /*_target*/, GLsizei /*_numAttachments*/, const GLenum* /*_attachments*/)
  914. {
  915. }
  916. static void GL_APIENTRY stubMultiDrawArraysIndirect(GLenum _mode, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  917. {
  918. const uint8_t* args = (const uint8_t*)_indirect;
  919. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  920. {
  921. GL_CHECK(glDrawArraysIndirect(_mode, (void*)args) );
  922. args += _stride;
  923. }
  924. }
  925. static void GL_APIENTRY stubMultiDrawElementsIndirect(GLenum _mode, GLenum _type, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  926. {
  927. const uint8_t* args = (const uint8_t*)_indirect;
  928. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  929. {
  930. GL_CHECK(glDrawElementsIndirect(_mode, _type, (void*)args) );
  931. args += _stride;
  932. }
  933. }
  934. static void GL_APIENTRY stubPolygonMode(GLenum /*_face*/, GLenum /*_mode*/)
  935. {
  936. }
  937. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  938. static const char* getGLString(GLenum _name)
  939. {
  940. const char* str = (const char*)glGetString(_name);
  941. glGetError(); // ignore error if glGetString returns NULL.
  942. if (NULL != str)
  943. {
  944. return str;
  945. }
  946. return "<unknown>";
  947. }
  948. static uint32_t getGLStringHash(GLenum _name)
  949. {
  950. const char* str = (const char*)glGetString(_name);
  951. glGetError(); // ignore error if glGetString returns NULL.
  952. if (NULL != str)
  953. {
  954. return bx::hashMurmur2A(str, (uint32_t)strlen(str) );
  955. }
  956. return 0;
  957. }
  958. void dumpExtensions(const char* _extensions)
  959. {
  960. if (NULL != _extensions)
  961. {
  962. char name[1024];
  963. const char* pos = _extensions;
  964. const char* end = _extensions + strlen(_extensions);
  965. while (pos < end)
  966. {
  967. uint32_t len;
  968. const char* space = strchr(pos, ' ');
  969. if (NULL != space)
  970. {
  971. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  972. }
  973. else
  974. {
  975. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  976. }
  977. strncpy(name, pos, len);
  978. name[len] = '\0';
  979. BX_TRACE("\t%s", name);
  980. pos += len+1;
  981. }
  982. }
  983. }
  984. const char* toString(GLenum _enum)
  985. {
  986. switch (_enum)
  987. {
  988. case GL_DEBUG_SOURCE_API: return "API";
  989. case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WinSys";
  990. case GL_DEBUG_SOURCE_SHADER_COMPILER: return "Shader";
  991. case GL_DEBUG_SOURCE_THIRD_PARTY: return "3rdparty";
  992. case GL_DEBUG_SOURCE_APPLICATION: return "Application";
  993. case GL_DEBUG_SOURCE_OTHER: return "Other";
  994. case GL_DEBUG_TYPE_ERROR: return "Error";
  995. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Deprecated behavior";
  996. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "Undefined behavior";
  997. case GL_DEBUG_TYPE_PORTABILITY: return "Portability";
  998. case GL_DEBUG_TYPE_PERFORMANCE: return "Performance";
  999. case GL_DEBUG_TYPE_OTHER: return "Other";
  1000. case GL_DEBUG_SEVERITY_HIGH: return "High";
  1001. case GL_DEBUG_SEVERITY_MEDIUM: return "Medium";
  1002. case GL_DEBUG_SEVERITY_LOW: return "Low";
  1003. case GL_DEBUG_SEVERITY_NOTIFICATION: return "SPAM";
  1004. default:
  1005. break;
  1006. }
  1007. return "<unknown>";
  1008. }
  1009. void GL_APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, const void* /*_userParam*/)
  1010. {
  1011. if (GL_DEBUG_SEVERITY_NOTIFICATION != _severity)
  1012. {
  1013. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  1014. , toString(_source)
  1015. , toString(_type)
  1016. , _id
  1017. , toString(_severity)
  1018. , _message
  1019. );
  1020. BX_UNUSED(_source, _type, _id, _severity, _message);
  1021. }
  1022. }
  1023. GLint glGet(GLenum _pname)
  1024. {
  1025. GLint result = 0;
  1026. glGetIntegerv(_pname, &result);
  1027. GLenum err = glGetError();
  1028. BX_WARN(0 == err, "glGetIntegerv(0x%04x, ...) failed with GL error: 0x%04x.", _pname, err);
  1029. return 0 == err ? result : 0;
  1030. }
  1031. void setTextureFormat(TextureFormat::Enum _format, GLenum _internalFmt, GLenum _fmt, GLenum _type = GL_ZERO)
  1032. {
  1033. TextureFormatInfo& tfi = s_textureFormat[_format];
  1034. tfi.m_internalFmt = _internalFmt;
  1035. tfi.m_fmt = _fmt;
  1036. tfi.m_type = _type;
  1037. }
  1038. void flushGlError()
  1039. {
  1040. for (GLenum err = glGetError(); err != 0; err = glGetError() );
  1041. }
  1042. GLenum initTestTexture(TextureFormat::Enum _format, bool _srgb, bool _mipmaps)
  1043. {
  1044. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1045. GLenum internalFmt = _srgb
  1046. ? tfi.m_internalFmtSrgb
  1047. : tfi.m_internalFmt
  1048. ;
  1049. GLsizei size = (16*16*getBitsPerPixel(_format) )/8;
  1050. void* data = bx::alignPtr(alloca(size+16), 0, 16);
  1051. flushGlError();
  1052. GLenum err = 0;
  1053. if (isCompressed(_format) )
  1054. {
  1055. glCompressedTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, size, data);
  1056. err |= glGetError();
  1057. if (_mipmaps)
  1058. {
  1059. glCompressedTexImage2D(GL_TEXTURE_2D, 1, internalFmt, 8, 8, 0, size, data);
  1060. err |= glGetError();
  1061. glCompressedTexImage2D(GL_TEXTURE_2D, 2, internalFmt, 4, 4, 0, size, data);
  1062. err |= glGetError();
  1063. glCompressedTexImage2D(GL_TEXTURE_2D, 3, internalFmt, 2, 2, 0, size, data);
  1064. err |= glGetError();
  1065. glCompressedTexImage2D(GL_TEXTURE_2D, 4, internalFmt, 1, 1, 0, size, data);
  1066. err |= glGetError();
  1067. }
  1068. }
  1069. else
  1070. {
  1071. glTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, tfi.m_fmt, tfi.m_type, data);
  1072. err |= glGetError();
  1073. if (_mipmaps)
  1074. {
  1075. glTexImage2D(GL_TEXTURE_2D, 1, internalFmt, 8, 8, 0, tfi.m_fmt, tfi.m_type, data);
  1076. err |= glGetError();
  1077. glTexImage2D(GL_TEXTURE_2D, 2, internalFmt, 4, 4, 0, tfi.m_fmt, tfi.m_type, data);
  1078. err |= glGetError();
  1079. glTexImage2D(GL_TEXTURE_2D, 3, internalFmt, 2, 2, 0, tfi.m_fmt, tfi.m_type, data);
  1080. err |= glGetError();
  1081. glTexImage2D(GL_TEXTURE_2D, 4, internalFmt, 1, 1, 0, tfi.m_fmt, tfi.m_type, data);
  1082. err |= glGetError();
  1083. }
  1084. }
  1085. return err;
  1086. }
  1087. static bool isTextureFormatValid(TextureFormat::Enum _format, bool _srgb = false, bool _mipAutogen = false)
  1088. {
  1089. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1090. GLenum internalFmt = _srgb
  1091. ? tfi.m_internalFmtSrgb
  1092. : tfi.m_internalFmt
  1093. ;
  1094. if (GL_ZERO == internalFmt)
  1095. {
  1096. return false;
  1097. }
  1098. GLuint id;
  1099. GL_CHECK(glGenTextures(1, &id) );
  1100. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1101. GLenum err = initTestTexture(_format, _srgb, _mipAutogen);
  1102. BX_WARN(0 == err, "TextureFormat::%s is not supported (%x: %s).", getName(_format), err, glEnumName(err) );
  1103. if (0 == err
  1104. && _mipAutogen)
  1105. {
  1106. glGenerateMipmap(GL_TEXTURE_2D);
  1107. err = glGetError();
  1108. }
  1109. GL_CHECK(glDeleteTextures(1, &id) );
  1110. return 0 == err;
  1111. }
  1112. static bool isImageFormatValid(TextureFormat::Enum _format)
  1113. {
  1114. if (GL_ZERO == s_imageFormat[_format])
  1115. {
  1116. return false;
  1117. }
  1118. GLuint id;
  1119. GL_CHECK(glGenTextures(1, &id) );
  1120. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1121. flushGlError();
  1122. GLenum err = 0;
  1123. glTexStorage2D(GL_TEXTURE_2D, 1, s_imageFormat[_format], 16, 16);
  1124. err |= glGetError();
  1125. if (0 == err)
  1126. {
  1127. glBindImageTexture(0
  1128. , id
  1129. , 0
  1130. , GL_FALSE
  1131. , 0
  1132. , GL_READ_WRITE
  1133. , s_imageFormat[_format]
  1134. );
  1135. err |= glGetError();
  1136. }
  1137. GL_CHECK(glDeleteTextures(1, &id) );
  1138. return 0 == err;
  1139. }
  1140. static bool isFramebufferFormatValid(TextureFormat::Enum _format, bool _srgb = false)
  1141. {
  1142. const TextureFormatInfo& tfi = s_textureFormat[_format];
  1143. GLenum internalFmt = _srgb
  1144. ? tfi.m_internalFmtSrgb
  1145. : tfi.m_internalFmt
  1146. ;
  1147. if (GL_ZERO == internalFmt
  1148. || !tfi.m_supported)
  1149. {
  1150. return false;
  1151. }
  1152. GLuint fbo;
  1153. GL_CHECK(glGenFramebuffers(1, &fbo) );
  1154. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, fbo) );
  1155. GLuint id;
  1156. GL_CHECK(glGenTextures(1, &id) );
  1157. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  1158. GLenum err = initTestTexture(_format, _srgb, false);
  1159. GLenum attachment;
  1160. if (isDepth(_format) )
  1161. {
  1162. const ImageBlockInfo& info = getBlockInfo(_format);
  1163. if (0 == info.depthBits)
  1164. {
  1165. attachment = GL_STENCIL_ATTACHMENT;
  1166. }
  1167. else if (0 == info.stencilBits)
  1168. {
  1169. attachment = GL_DEPTH_ATTACHMENT;
  1170. }
  1171. else
  1172. {
  1173. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  1174. }
  1175. }
  1176. else
  1177. {
  1178. attachment = GL_COLOR_ATTACHMENT0;
  1179. }
  1180. glFramebufferTexture2D(GL_FRAMEBUFFER
  1181. , attachment
  1182. , GL_TEXTURE_2D
  1183. , id
  1184. , 0
  1185. );
  1186. err = glGetError();
  1187. if (0 == err)
  1188. {
  1189. err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  1190. }
  1191. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1192. GL_CHECK(glDeleteFramebuffers(1, &fbo) );
  1193. GL_CHECK(glDeleteTextures(1, &id) );
  1194. return GL_FRAMEBUFFER_COMPLETE == err;
  1195. }
  1196. static void getFilters(uint32_t _flags, bool _hasMips, GLenum& _magFilter, GLenum& _minFilter)
  1197. {
  1198. const uint32_t mag = (_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT;
  1199. const uint32_t min = (_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT;
  1200. const uint32_t mip = (_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT;
  1201. _magFilter = s_textureFilterMag[mag];
  1202. _minFilter = s_textureFilterMin[min][_hasMips ? mip+1 : 0];
  1203. }
  1204. void updateExtension(const char* _name)
  1205. {
  1206. bool supported = false;
  1207. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1208. {
  1209. Extension& extension = s_extension[ii];
  1210. if (!extension.m_supported
  1211. && extension.m_initialize)
  1212. {
  1213. const char* ext = _name;
  1214. if (0 == strncmp(ext, "GL_", 3) ) // skip GL_
  1215. {
  1216. ext += 3;
  1217. }
  1218. if (0 == strcmp(ext, extension.m_name) )
  1219. {
  1220. extension.m_supported = true;
  1221. supported = true;
  1222. break;
  1223. }
  1224. }
  1225. }
  1226. BX_TRACE("GL_EXTENSION %s: %s", supported ? " (supported)" : "", _name);
  1227. BX_UNUSED(supported);
  1228. }
  1229. #if BGFX_CONFIG_USE_OVR
  1230. class VRImplOVRGL : public VRImplOVR
  1231. {
  1232. public:
  1233. VRImplOVRGL();
  1234. virtual bool createSwapChain(const VRDesc& _desc, int _msaaSamples, int _mirrorWidth, int _mirrorHeight) BX_OVERRIDE;
  1235. virtual void destroySwapChain() BX_OVERRIDE;
  1236. virtual void destroyMirror() BX_OVERRIDE;
  1237. virtual void renderEyeStart(const VRDesc& _desc, uint8_t _eye) BX_OVERRIDE;
  1238. virtual bool submitSwapChain(const VRDesc& _desc) BX_OVERRIDE;
  1239. private:
  1240. GLuint m_eyeFbo[2];
  1241. GLuint m_eyeTexId[2][4];
  1242. GLuint m_depthBuffer[2];
  1243. GLuint m_msaaEyeFbo[2];
  1244. GLuint m_msaaEyeTexId[2];
  1245. GLuint m_msaaDepthBuffer[2];
  1246. GLuint m_mirrorFbo;
  1247. GLint m_mirrorWidth;
  1248. GLint m_mirrorHeight;
  1249. ovrTextureSwapChain m_textureSwapChain[2];
  1250. ovrMirrorTexture m_mirrorTexture;
  1251. };
  1252. #endif // BGFX_CONFIG_USE_OVR
  1253. struct VendorId
  1254. {
  1255. const char* name;
  1256. uint16_t id;
  1257. };
  1258. static const VendorId s_vendorIds[] =
  1259. {
  1260. { "NVIDIA Corporation", BGFX_PCI_ID_NVIDIA },
  1261. { "Advanced Micro Devices, Inc.", BGFX_PCI_ID_AMD },
  1262. { "Intel", BGFX_PCI_ID_INTEL },
  1263. };
  1264. struct RendererContextGL : public RendererContextI
  1265. {
  1266. RendererContextGL()
  1267. : m_numWindows(1)
  1268. , m_rtMsaa(false)
  1269. , m_fbDiscard(BGFX_CLEAR_NONE)
  1270. , m_capture(NULL)
  1271. , m_captureSize(0)
  1272. , m_maxAnisotropy(0.0f)
  1273. , m_maxAnisotropyDefault(0.0f)
  1274. , m_maxMsaa(0)
  1275. , m_vao(0)
  1276. , m_blitSupported(false)
  1277. , m_readBackSupported(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1278. , m_vaoSupport(false)
  1279. , m_samplerObjectSupport(false)
  1280. , m_shadowSamplersSupport(false)
  1281. , m_srgbWriteControlSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1282. , m_borderColorSupport(BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1283. , m_programBinarySupport(false)
  1284. , m_textureSwizzleSupport(false)
  1285. , m_depthTextureSupport(false)
  1286. , m_timerQuerySupport(false)
  1287. , m_occlusionQuerySupport(false)
  1288. , m_atocSupport(false)
  1289. , m_conservativeRasterSupport(false)
  1290. , m_flip(false)
  1291. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1292. , m_backBufferFbo(0)
  1293. , m_msaaBackBufferFbo(0)
  1294. {
  1295. memset(m_msaaBackBufferRbos, 0, sizeof(m_msaaBackBufferRbos) );
  1296. }
  1297. ~RendererContextGL()
  1298. {
  1299. }
  1300. void init()
  1301. {
  1302. m_renderdocdll = loadRenderDoc();
  1303. m_fbh.idx = invalidHandle;
  1304. memset(m_uniforms, 0, sizeof(m_uniforms) );
  1305. memset(&m_resolution, 0, sizeof(m_resolution) );
  1306. setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  1307. // Must be after context is initialized?!
  1308. VRImplI* vrImpl = NULL;
  1309. #if BGFX_CONFIG_USE_OVR
  1310. vrImpl = &m_ovrRender;
  1311. #endif
  1312. m_ovr.init(vrImpl);
  1313. m_vendor = getGLString(GL_VENDOR);
  1314. m_renderer = getGLString(GL_RENDERER);
  1315. m_version = getGLString(GL_VERSION);
  1316. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  1317. for (uint32_t ii = 0; ii < BX_COUNTOF(s_vendorIds); ++ii)
  1318. {
  1319. const VendorId& vendorId = s_vendorIds[ii];
  1320. if (0 == strncmp(vendorId.name, m_vendor, strlen(vendorId.name) ) )
  1321. {
  1322. g_caps.vendorId = vendorId.id;
  1323. break;
  1324. }
  1325. }
  1326. GLint numCmpFormats = 0;
  1327. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1328. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1329. GLint* cmpFormat = NULL;
  1330. if (0 < numCmpFormats)
  1331. {
  1332. numCmpFormats = numCmpFormats > 256 ? 256 : numCmpFormats;
  1333. cmpFormat = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1334. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, cmpFormat) );
  1335. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1336. {
  1337. GLint internalFmt = cmpFormat[ii];
  1338. uint32_t fmt = uint32_t(TextureFormat::Unknown);
  1339. for (uint32_t jj = 0; jj < fmt; ++jj)
  1340. {
  1341. if (s_textureFormat[jj].m_internalFmt == (GLenum)internalFmt)
  1342. {
  1343. s_textureFormat[jj].m_supported = true;
  1344. fmt = jj;
  1345. }
  1346. }
  1347. BX_TRACE(" %3d: %8x %s", ii, internalFmt, getName( (TextureFormat::Enum)fmt) );
  1348. }
  1349. }
  1350. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1351. {
  1352. #define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  1353. BX_TRACE("Defaults:");
  1354. #if BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1355. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1356. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1357. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1358. #else
  1359. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  1360. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  1361. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  1362. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1363. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1364. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1365. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1366. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1367. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1368. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1369. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1370. GL_GET(GL_MAX_COLOR_ATTACHMENTS, 1);
  1371. GL_GET(GL_MAX_DRAW_BUFFERS, 1);
  1372. #undef GL_GET
  1373. BX_TRACE(" Vendor: %s", m_vendor);
  1374. BX_TRACE(" Renderer: %s", m_renderer);
  1375. BX_TRACE(" Version: %s", m_version);
  1376. BX_TRACE("GLSL version: %s", m_glslVersion);
  1377. }
  1378. // Initial binary shader hash depends on driver version.
  1379. m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1380. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  1381. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  1382. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  1383. ;
  1384. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1385. && 0 == strcmp(m_vendor, "Imagination Technologies")
  1386. && NULL != strstr(m_version, "(SDK 3.5@3510720)") )
  1387. {
  1388. // Skip initializing extensions that are broken in emulator.
  1389. s_extension[Extension::ARB_program_interface_query ].m_initialize =
  1390. s_extension[Extension::ARB_shader_storage_buffer_object].m_initialize = false;
  1391. }
  1392. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  1393. {
  1394. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  1395. glGetError(); // ignore error if glGetString returns NULL.
  1396. if (NULL != extensions)
  1397. {
  1398. char name[1024];
  1399. const char* pos = extensions;
  1400. const char* end = extensions + strlen(extensions);
  1401. uint32_t index = 0;
  1402. while (pos < end)
  1403. {
  1404. uint32_t len;
  1405. const char* space = strchr(pos, ' ');
  1406. if (NULL != space)
  1407. {
  1408. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  1409. }
  1410. else
  1411. {
  1412. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  1413. }
  1414. strncpy(name, pos, len);
  1415. name[len] = '\0';
  1416. updateExtension(name);
  1417. pos += len+1;
  1418. ++index;
  1419. }
  1420. }
  1421. else if (NULL != glGetStringi)
  1422. {
  1423. GLint numExtensions = 0;
  1424. glGetIntegerv(GL_NUM_EXTENSIONS, &numExtensions);
  1425. glGetError(); // ignore error if glGetIntegerv returns NULL.
  1426. for (GLint index = 0; index < numExtensions; ++index)
  1427. {
  1428. const char* name = (const char*)glGetStringi(GL_EXTENSIONS, index);
  1429. updateExtension(name);
  1430. }
  1431. }
  1432. BX_TRACE("Supported extensions:");
  1433. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1434. {
  1435. if (s_extension[ii].m_supported)
  1436. {
  1437. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  1438. }
  1439. }
  1440. }
  1441. // Allow all texture filters.
  1442. memset(s_textureFilter, true, BX_COUNTOF(s_textureFilter) );
  1443. bool bc123Supported = 0
  1444. || s_extension[Extension::EXT_texture_compression_s3tc ].m_supported
  1445. || s_extension[Extension::MOZ_WEBGL_compressed_texture_s3tc ].m_supported
  1446. || s_extension[Extension::WEBGL_compressed_texture_s3tc ].m_supported
  1447. || s_extension[Extension::WEBKIT_WEBGL_compressed_texture_s3tc].m_supported
  1448. ;
  1449. s_textureFormat[TextureFormat::BC1].m_supported |= bc123Supported
  1450. || s_extension[Extension::ANGLE_texture_compression_dxt1].m_supported
  1451. || s_extension[Extension::EXT_texture_compression_dxt1 ].m_supported
  1452. ;
  1453. if (!s_textureFormat[TextureFormat::BC1].m_supported
  1454. && ( s_textureFormat[TextureFormat::BC2].m_supported || s_textureFormat[TextureFormat::BC3].m_supported) )
  1455. {
  1456. // If RGBA_S3TC_DXT1 is not supported, maybe RGB_S3TC_DXT1 is?
  1457. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1458. {
  1459. if (GL_COMPRESSED_RGB_S3TC_DXT1_EXT == cmpFormat[ii])
  1460. {
  1461. setTextureFormat(TextureFormat::BC1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
  1462. s_textureFormat[TextureFormat::BC1].m_supported = true;
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. s_textureFormat[TextureFormat::BC2].m_supported |= bc123Supported
  1468. || s_extension[Extension::ANGLE_texture_compression_dxt3 ].m_supported
  1469. || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported
  1470. ;
  1471. s_textureFormat[TextureFormat::BC3].m_supported |= bc123Supported
  1472. || s_extension[Extension::ANGLE_texture_compression_dxt5 ].m_supported
  1473. || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported
  1474. ;
  1475. if (s_extension[Extension::EXT_texture_compression_latc].m_supported)
  1476. {
  1477. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT);
  1478. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT);
  1479. }
  1480. if (s_extension[Extension::ARB_texture_compression_rgtc].m_supported
  1481. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  1482. {
  1483. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1);
  1484. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2);
  1485. }
  1486. bool etc1Supported = 0
  1487. || s_extension[Extension::OES_compressed_ETC1_RGB8_texture].m_supported
  1488. || s_extension[Extension::WEBGL_compressed_texture_etc1 ].m_supported
  1489. ;
  1490. s_textureFormat[TextureFormat::ETC1].m_supported |= etc1Supported;
  1491. bool etc2Supported = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1492. || s_extension[Extension::ARB_ES3_compatibility].m_supported
  1493. ;
  1494. s_textureFormat[TextureFormat::ETC2 ].m_supported |= etc2Supported;
  1495. s_textureFormat[TextureFormat::ETC2A ].m_supported |= etc2Supported;
  1496. s_textureFormat[TextureFormat::ETC2A1].m_supported |= etc2Supported;
  1497. if (!s_textureFormat[TextureFormat::ETC1].m_supported
  1498. && s_textureFormat[TextureFormat::ETC2].m_supported)
  1499. {
  1500. // When ETC2 is supported override ETC1 texture format settings.
  1501. s_textureFormat[TextureFormat::ETC1].m_internalFmt = GL_COMPRESSED_RGB8_ETC2;
  1502. s_textureFormat[TextureFormat::ETC1].m_fmt = GL_COMPRESSED_RGB8_ETC2;
  1503. s_textureFormat[TextureFormat::ETC1].m_supported = true;
  1504. }
  1505. bool ptc1Supported = 0
  1506. || s_extension[Extension::IMG_texture_compression_pvrtc ].m_supported
  1507. || s_extension[Extension::WEBGL_compressed_texture_pvrtc].m_supported
  1508. ;
  1509. s_textureFormat[TextureFormat::PTC12 ].m_supported |= ptc1Supported;
  1510. s_textureFormat[TextureFormat::PTC14 ].m_supported |= ptc1Supported;
  1511. s_textureFormat[TextureFormat::PTC12A].m_supported |= ptc1Supported;
  1512. s_textureFormat[TextureFormat::PTC14A].m_supported |= ptc1Supported;
  1513. bool ptc2Supported = s_extension[Extension::IMG_texture_compression_pvrtc2].m_supported;
  1514. s_textureFormat[TextureFormat::PTC22].m_supported |= ptc2Supported;
  1515. s_textureFormat[TextureFormat::PTC24].m_supported |= ptc2Supported;
  1516. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1517. {
  1518. setTextureFormat(TextureFormat::D32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
  1519. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  1520. {
  1521. setTextureFormat(TextureFormat::RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT);
  1522. setTextureFormat(TextureFormat::RGBA32F, GL_RGBA, GL_RGBA, GL_FLOAT);
  1523. // internalFormat and format must match:
  1524. // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexImage2D.xml
  1525. setTextureFormat(TextureFormat::RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE);
  1526. setTextureFormat(TextureFormat::R5G6B5, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5_REV);
  1527. setTextureFormat(TextureFormat::RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV);
  1528. setTextureFormat(TextureFormat::RGB5A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV);
  1529. if (s_extension[Extension::OES_texture_half_float].m_supported
  1530. || s_extension[Extension::OES_texture_float ].m_supported)
  1531. {
  1532. // https://www.khronos.org/registry/gles/extensions/OES/OES_texture_float.txt
  1533. // When half/float is available via extensions texture will be marked as
  1534. // incomplete if it uses anything other than nearest filter.
  1535. const bool linear16F = s_extension[Extension::OES_texture_half_float_linear].m_supported;
  1536. const bool linear32F = s_extension[Extension::OES_texture_float_linear ].m_supported;
  1537. s_textureFilter[TextureFormat::R16F] = linear16F;
  1538. s_textureFilter[TextureFormat::RG16F] = linear16F;
  1539. s_textureFilter[TextureFormat::RGBA16F] = linear16F;
  1540. s_textureFilter[TextureFormat::R32F] = linear32F;
  1541. s_textureFilter[TextureFormat::RG32F] = linear32F;
  1542. s_textureFilter[TextureFormat::RGBA32F] = linear32F;
  1543. }
  1544. if (BX_ENABLED(BX_PLATFORM_IOS) )
  1545. {
  1546. setTextureFormat(TextureFormat::D16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT);
  1547. setTextureFormat(TextureFormat::D24S8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
  1548. }
  1549. }
  1550. }
  1551. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1552. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1553. {
  1554. setTextureFormat(TextureFormat::R8I, GL_R8I, GL_RED_INTEGER, GL_BYTE);
  1555. setTextureFormat(TextureFormat::R8U, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE);
  1556. setTextureFormat(TextureFormat::R16I, GL_R16I, GL_RED_INTEGER, GL_SHORT);
  1557. setTextureFormat(TextureFormat::R16U, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT);
  1558. // setTextureFormat(TextureFormat::RG16, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT);
  1559. // setTextureFormat(TextureFormat::RGBA16, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT);
  1560. setTextureFormat(TextureFormat::R32U, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
  1561. setTextureFormat(TextureFormat::RG32U, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT);
  1562. setTextureFormat(TextureFormat::RGBA32U, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
  1563. }
  1564. if (s_extension[Extension::EXT_texture_format_BGRA8888 ].m_supported
  1565. || s_extension[Extension::EXT_bgra ].m_supported
  1566. || s_extension[Extension::IMG_texture_format_BGRA8888 ].m_supported
  1567. || s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1568. {
  1569. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1570. {
  1571. m_readPixelsFmt = GL_BGRA;
  1572. }
  1573. // Mixing GLES and GL extensions here. OpenGL EXT_bgra and
  1574. // APPLE_texture_format_BGRA8888 wants
  1575. // format to be BGRA but internal format to stay RGBA, but
  1576. // EXT_texture_format_BGRA8888 wants both format and internal
  1577. // format to be BGRA.
  1578. //
  1579. // Reference:
  1580. // https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt
  1581. // https://www.opengl.org/registry/specs/EXT/bgra.txt
  1582. // https://www.khronos.org/registry/gles/extensions/APPLE/APPLE_texture_format_BGRA8888.txt
  1583. if (!s_extension[Extension::EXT_bgra ].m_supported
  1584. && !s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1585. {
  1586. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA;
  1587. }
  1588. if (!isTextureFormatValid(TextureFormat::BGRA8) )
  1589. {
  1590. // Revert back to RGBA if texture can't be created.
  1591. setTextureFormat(TextureFormat::BGRA8, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE);
  1592. }
  1593. }
  1594. if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  1595. || !isTextureFormatValid(TextureFormat::R8) )
  1596. {
  1597. // GL core has to use GL_R8 Issue#208, GLES2 has to use GL_LUMINANCE issue#226
  1598. s_textureFormat[TextureFormat::R8].m_internalFmt = GL_LUMINANCE;
  1599. s_textureFormat[TextureFormat::R8].m_fmt = GL_LUMINANCE;
  1600. }
  1601. for (uint32_t ii = BX_ENABLED(BX_PLATFORM_IOS) ? TextureFormat::Unknown : 0 // skip test on iOS!
  1602. ; ii < TextureFormat::Count
  1603. ; ++ii
  1604. )
  1605. {
  1606. if (TextureFormat::Unknown != ii
  1607. && TextureFormat::UnknownDepth != ii)
  1608. {
  1609. s_textureFormat[ii].m_supported = isTextureFormatValid(TextureFormat::Enum(ii) );
  1610. }
  1611. }
  1612. if (BX_ENABLED(0) )
  1613. {
  1614. // Disable all compressed texture formats. For testing only.
  1615. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii)
  1616. {
  1617. s_textureFormat[ii].m_supported = false;
  1618. }
  1619. }
  1620. const bool computeSupport = false
  1621. || !!(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1622. || s_extension[Extension::ARB_compute_shader].m_supported
  1623. ;
  1624. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1625. {
  1626. uint16_t supported = BGFX_CAPS_FORMAT_TEXTURE_NONE;
  1627. supported |= s_textureFormat[ii].m_supported
  1628. ? BGFX_CAPS_FORMAT_TEXTURE_2D
  1629. | BGFX_CAPS_FORMAT_TEXTURE_3D
  1630. | BGFX_CAPS_FORMAT_TEXTURE_CUBE
  1631. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1632. ;
  1633. supported |= isTextureFormatValid(TextureFormat::Enum(ii), true)
  1634. ? BGFX_CAPS_FORMAT_TEXTURE_2D_SRGB
  1635. | BGFX_CAPS_FORMAT_TEXTURE_3D_SRGB
  1636. | BGFX_CAPS_FORMAT_TEXTURE_CUBE_SRGB
  1637. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1638. ;
  1639. supported |= isTextureFormatValid(TextureFormat::Enum(ii), false, true)
  1640. ? BGFX_CAPS_FORMAT_TEXTURE_MIP_AUTOGEN
  1641. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1642. ;
  1643. supported |= computeSupport
  1644. && isImageFormatValid(TextureFormat::Enum(ii) )
  1645. ? BGFX_CAPS_FORMAT_TEXTURE_IMAGE
  1646. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1647. ;
  1648. supported |= isFramebufferFormatValid(TextureFormat::Enum(ii) )
  1649. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  1650. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1651. ;
  1652. if (NULL != glGetInternalformativ)
  1653. {
  1654. GLint maxSamples;
  1655. glGetInternalformativ(GL_RENDERBUFFER
  1656. , s_textureFormat[ii].m_internalFmt
  1657. , GL_SAMPLES
  1658. , 1
  1659. , &maxSamples
  1660. );
  1661. GLenum err = glGetError();
  1662. supported |= 0 == err && maxSamples > 0
  1663. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER_MSAA
  1664. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1665. ;
  1666. glGetInternalformativ(GL_TEXTURE_2D_MULTISAMPLE
  1667. , s_textureFormat[ii].m_internalFmt
  1668. , GL_SAMPLES
  1669. , 1
  1670. , &maxSamples
  1671. );
  1672. err = glGetError();
  1673. supported |= 0 == err && maxSamples > 0
  1674. ? BGFX_CAPS_FORMAT_TEXTURE_MSAA
  1675. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1676. ;
  1677. }
  1678. g_caps.formats[ii] = supported;
  1679. }
  1680. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1681. || s_extension[Extension::OES_texture_3D].m_supported
  1682. ? BGFX_CAPS_TEXTURE_3D
  1683. : 0
  1684. ;
  1685. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1686. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1687. ? BGFX_CAPS_TEXTURE_COMPARE_ALL
  1688. : 0
  1689. ;
  1690. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1691. || s_extension[Extension::OES_vertex_half_float].m_supported
  1692. ? BGFX_CAPS_VERTEX_ATTRIB_HALF
  1693. : 0
  1694. ;
  1695. g_caps.supported |= false
  1696. || s_extension[Extension::ARB_vertex_type_2_10_10_10_rev].m_supported
  1697. || s_extension[Extension::OES_vertex_type_10_10_10_2].m_supported
  1698. ? BGFX_CAPS_VERTEX_ATTRIB_UINT10
  1699. : 0
  1700. ;
  1701. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1702. || s_extension[Extension::EXT_frag_depth].m_supported
  1703. ? BGFX_CAPS_FRAGMENT_DEPTH
  1704. : 0
  1705. ;
  1706. g_caps.supported |= s_extension[Extension::ARB_draw_buffers_blend].m_supported
  1707. ? BGFX_CAPS_BLEND_INDEPENDENT
  1708. : 0
  1709. ;
  1710. g_caps.supported |= s_extension[Extension::INTEL_fragment_shader_ordering].m_supported
  1711. ? BGFX_CAPS_FRAGMENT_ORDERING
  1712. : 0
  1713. ;
  1714. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1715. || s_extension[Extension::OES_element_index_uint].m_supported
  1716. ? BGFX_CAPS_INDEX32
  1717. : 0
  1718. ;
  1719. const bool drawIndirectSupported = false
  1720. || s_extension[Extension::AMD_multi_draw_indirect].m_supported
  1721. || s_extension[Extension::ARB_draw_indirect ].m_supported
  1722. || s_extension[Extension::ARB_multi_draw_indirect].m_supported
  1723. || s_extension[Extension::EXT_multi_draw_indirect].m_supported
  1724. ;
  1725. if (drawIndirectSupported)
  1726. {
  1727. if (NULL == glMultiDrawArraysIndirect
  1728. || NULL == glMultiDrawElementsIndirect)
  1729. {
  1730. glMultiDrawArraysIndirect = stubMultiDrawArraysIndirect;
  1731. glMultiDrawElementsIndirect = stubMultiDrawElementsIndirect;
  1732. }
  1733. }
  1734. g_caps.supported |= drawIndirectSupported
  1735. ? BGFX_CAPS_DRAW_INDIRECT
  1736. : 0
  1737. ;
  1738. if (NULL == glPolygonMode)
  1739. {
  1740. glPolygonMode = stubPolygonMode;
  1741. }
  1742. if (s_extension[Extension::ARB_copy_image].m_supported
  1743. || s_extension[Extension::EXT_copy_image].m_supported
  1744. || s_extension[Extension:: NV_copy_image].m_supported
  1745. || s_extension[Extension::OES_copy_image].m_supported)
  1746. {
  1747. m_blitSupported = NULL != glCopyImageSubData;
  1748. g_caps.supported |= m_blitSupported
  1749. ? BGFX_CAPS_TEXTURE_BLIT
  1750. : 0
  1751. ;
  1752. }
  1753. g_caps.supported |= m_readBackSupported
  1754. ? BGFX_CAPS_TEXTURE_READ_BACK
  1755. : 0
  1756. ;
  1757. g_caps.supported |= false
  1758. || s_extension[Extension::EXT_texture_array].m_supported
  1759. || s_extension[Extension::EXT_gpu_shader4].m_supported
  1760. || !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1761. ? BGFX_CAPS_TEXTURE_2D_ARRAY
  1762. : 0
  1763. ;
  1764. g_caps.supported |= false
  1765. || s_extension[Extension::ARB_texture_cube_map_array].m_supported
  1766. || s_extension[Extension::EXT_texture_cube_map_array].m_supported
  1767. ? BGFX_CAPS_TEXTURE_CUBE_ARRAY
  1768. : 0
  1769. ;
  1770. g_caps.limits.maxTextureSize = uint16_t(glGet(GL_MAX_TEXTURE_SIZE) );
  1771. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1772. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1773. || s_extension[Extension::EXT_draw_buffers ].m_supported
  1774. || s_extension[Extension::WEBGL_draw_buffers].m_supported)
  1775. {
  1776. g_caps.limits.maxFBAttachments = uint8_t(bx::uint32_min(glGet(GL_MAX_DRAW_BUFFERS)
  1777. , BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS)
  1778. );
  1779. }
  1780. // if (s_extension[Extension::ARB_clip_control].m_supported)
  1781. // {
  1782. // GL_CHECK(glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE) );
  1783. // g_caps.originBottomLeft = true;
  1784. // }
  1785. // else
  1786. {
  1787. g_caps.homogeneousDepth = true;
  1788. g_caps.originBottomLeft = true;
  1789. }
  1790. m_vaoSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1791. || s_extension[Extension::ARB_vertex_array_object].m_supported
  1792. || s_extension[Extension::OES_vertex_array_object].m_supported
  1793. ;
  1794. if (BX_ENABLED(BX_PLATFORM_NACL) )
  1795. {
  1796. m_vaoSupport &= true
  1797. && NULL != glGenVertexArrays
  1798. && NULL != glDeleteVertexArrays
  1799. && NULL != glBindVertexArray
  1800. ;
  1801. }
  1802. if (m_vaoSupport)
  1803. {
  1804. GL_CHECK(glGenVertexArrays(1, &m_vao) );
  1805. }
  1806. m_samplerObjectSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1807. || s_extension[Extension::ARB_sampler_objects].m_supported
  1808. ;
  1809. m_shadowSamplersSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1810. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1811. ;
  1812. m_programBinarySupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1813. || s_extension[Extension::ARB_get_program_binary].m_supported
  1814. || s_extension[Extension::OES_get_program_binary].m_supported
  1815. || s_extension[Extension::IMG_shader_binary ].m_supported
  1816. ;
  1817. m_textureSwizzleSupport = false
  1818. || s_extension[Extension::ARB_texture_swizzle].m_supported
  1819. || s_extension[Extension::EXT_texture_swizzle].m_supported
  1820. ;
  1821. m_depthTextureSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1822. || s_extension[Extension::ANGLE_depth_texture ].m_supported
  1823. || s_extension[Extension::CHROMIUM_depth_texture ].m_supported
  1824. || s_extension[Extension::GOOGLE_depth_texture ].m_supported
  1825. || s_extension[Extension::OES_depth_texture ].m_supported
  1826. || s_extension[Extension::MOZ_WEBGL_depth_texture ].m_supported
  1827. || s_extension[Extension::WEBGL_depth_texture ].m_supported
  1828. || s_extension[Extension::WEBKIT_WEBGL_depth_texture].m_supported
  1829. ;
  1830. m_timerQuerySupport = false
  1831. || s_extension[Extension::ANGLE_timer_query ].m_supported
  1832. || s_extension[Extension::ARB_timer_query ].m_supported
  1833. || s_extension[Extension::EXT_disjoint_timer_query].m_supported
  1834. || s_extension[Extension::EXT_timer_query ].m_supported
  1835. ;
  1836. m_timerQuerySupport &= true
  1837. && NULL != glQueryCounter
  1838. && NULL != glGetQueryObjectiv
  1839. && NULL != glGetQueryObjectui64v
  1840. ;
  1841. m_occlusionQuerySupport = false
  1842. || s_extension[Extension::ARB_occlusion_query ].m_supported
  1843. || s_extension[Extension::ARB_occlusion_query2 ].m_supported
  1844. || s_extension[Extension::EXT_occlusion_query_boolean].m_supported
  1845. || s_extension[Extension::NV_occlusion_query ].m_supported
  1846. ;
  1847. m_occlusionQuerySupport &= true
  1848. && NULL != glGenQueries
  1849. && NULL != glDeleteQueries
  1850. && NULL != glBeginQuery
  1851. && NULL != glEndQuery
  1852. ;
  1853. m_atocSupport = s_extension[Extension::ARB_multisample].m_supported;
  1854. m_conservativeRasterSupport = s_extension[Extension::NV_conservative_raster].m_supported;
  1855. g_caps.supported |= 0
  1856. | (m_atocSupport ? BGFX_CAPS_ALPHA_TO_COVERAGE : 0)
  1857. | (m_conservativeRasterSupport ? BGFX_CAPS_CONSERVATIVE_RASTER : 0)
  1858. | (m_occlusionQuerySupport ? BGFX_CAPS_OCCLUSION_QUERY : 0)
  1859. | (m_depthTextureSupport ? BGFX_CAPS_TEXTURE_COMPARE_LEQUAL : 0)
  1860. | (computeSupport ? BGFX_CAPS_COMPUTE : 0)
  1861. ;
  1862. g_caps.supported |= m_glctx.getCaps();
  1863. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1864. {
  1865. m_srgbWriteControlSupport = s_extension[Extension::EXT_sRGB_write_control].m_supported;
  1866. m_borderColorSupport = s_extension[Extension::NV_texture_border_clamp].m_supported;
  1867. s_textureAddress[BGFX_TEXTURE_U_BORDER>>BGFX_TEXTURE_U_SHIFT] = s_extension[Extension::NV_texture_border_clamp].m_supported
  1868. ? GL_CLAMP_TO_BORDER
  1869. : GL_CLAMP_TO_EDGE
  1870. ;
  1871. }
  1872. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  1873. {
  1874. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &m_maxAnisotropyDefault) );
  1875. }
  1876. if (s_extension[Extension::ARB_texture_multisample].m_supported
  1877. || s_extension[Extension::ANGLE_framebuffer_multisample].m_supported)
  1878. {
  1879. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &m_maxMsaa) );
  1880. }
  1881. if (s_extension[Extension::OES_read_format].m_supported
  1882. && (s_extension[Extension::IMG_read_format].m_supported || s_extension[Extension::EXT_read_format_bgra].m_supported) )
  1883. {
  1884. m_readPixelsFmt = GL_BGRA;
  1885. }
  1886. else
  1887. {
  1888. m_readPixelsFmt = GL_RGBA;
  1889. }
  1890. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1891. {
  1892. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1893. }
  1894. else
  1895. {
  1896. if (s_extension[Extension::ANGLE_instanced_arrays].m_supported
  1897. || s_extension[Extension::ARB_instanced_arrays].m_supported
  1898. || s_extension[Extension::EXT_instanced_arrays].m_supported)
  1899. {
  1900. if (NULL != glVertexAttribDivisor
  1901. && NULL != glDrawArraysInstanced
  1902. && NULL != glDrawElementsInstanced)
  1903. {
  1904. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1905. }
  1906. }
  1907. if (0 == (g_caps.supported & BGFX_CAPS_INSTANCING) )
  1908. {
  1909. glVertexAttribDivisor = stubVertexAttribDivisor;
  1910. glDrawArraysInstanced = stubDrawArraysInstanced;
  1911. glDrawElementsInstanced = stubDrawElementsInstanced;
  1912. }
  1913. }
  1914. if (s_extension[Extension::ARB_debug_output].m_supported
  1915. || s_extension[Extension::KHR_debug].m_supported)
  1916. {
  1917. if (NULL != glDebugMessageControl
  1918. && NULL != glDebugMessageInsert
  1919. && NULL != glDebugMessageCallback
  1920. && NULL != glGetDebugMessageLog)
  1921. {
  1922. GL_CHECK(glDebugMessageCallback(debugProcCb, NULL) );
  1923. GL_CHECK(glDebugMessageControl(GL_DONT_CARE
  1924. , GL_DONT_CARE
  1925. , GL_DEBUG_SEVERITY_MEDIUM
  1926. , 0
  1927. , NULL
  1928. , GL_TRUE
  1929. ) );
  1930. }
  1931. }
  1932. if (s_extension[Extension::ARB_seamless_cube_map].m_supported)
  1933. {
  1934. GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) );
  1935. }
  1936. if (NULL == glFrameTerminatorGREMEDY
  1937. || !s_extension[Extension::GREMEDY_frame_terminator].m_supported)
  1938. {
  1939. glFrameTerminatorGREMEDY = stubFrameTerminatorGREMEDY;
  1940. }
  1941. if (NULL == glInsertEventMarker
  1942. || !s_extension[Extension::EXT_debug_marker].m_supported)
  1943. {
  1944. glInsertEventMarker = (NULL != glStringMarkerGREMEDY && s_extension[Extension::GREMEDY_string_marker].m_supported)
  1945. ? stubInsertEventMarkerGREMEDY
  1946. : stubInsertEventMarker
  1947. ;
  1948. }
  1949. setGraphicsDebuggerPresent(s_extension[Extension::EXT_debug_tool].m_supported);
  1950. if (NULL == glObjectLabel)
  1951. {
  1952. glObjectLabel = stubObjectLabel;
  1953. }
  1954. if (NULL == glInvalidateFramebuffer)
  1955. {
  1956. glInvalidateFramebuffer = stubInvalidateFramebuffer;
  1957. }
  1958. if (m_timerQuerySupport)
  1959. {
  1960. m_gpuTimer.create();
  1961. }
  1962. if (m_occlusionQuerySupport)
  1963. {
  1964. m_occlusionQuery.create();
  1965. }
  1966. // Init reserved part of view name.
  1967. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1968. {
  1969. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  1970. }
  1971. ovrPostReset();
  1972. BGFX_GPU_PROFILER_BIND();
  1973. }
  1974. void shutdown()
  1975. {
  1976. BGFX_GPU_PROFILER_UNBIND();
  1977. ovrPreReset();
  1978. m_ovr.shutdown();
  1979. if (m_vaoSupport)
  1980. {
  1981. GL_CHECK(glBindVertexArray(0) );
  1982. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  1983. m_vao = 0;
  1984. }
  1985. captureFinish();
  1986. invalidateCache();
  1987. if (m_timerQuerySupport)
  1988. {
  1989. m_gpuTimer.destroy();
  1990. }
  1991. if (m_occlusionQuerySupport)
  1992. {
  1993. m_occlusionQuery.destroy();
  1994. }
  1995. destroyMsaaFbo();
  1996. m_glctx.destroy();
  1997. m_flip = false;
  1998. unloadRenderDoc(m_renderdocdll);
  1999. }
  2000. RendererType::Enum getRendererType() const BX_OVERRIDE
  2001. {
  2002. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  2003. {
  2004. return RendererType::OpenGL;
  2005. }
  2006. return RendererType::OpenGLES;
  2007. }
  2008. const char* getRendererName() const BX_OVERRIDE
  2009. {
  2010. return BGFX_RENDERER_OPENGL_NAME;
  2011. }
  2012. void flip(HMD& _hmd)
  2013. {
  2014. if (m_flip)
  2015. {
  2016. for (uint32_t ii = 1, num = m_numWindows; ii < num; ++ii)
  2017. {
  2018. m_glctx.swap(m_frameBuffers[m_windows[ii].idx].m_swapChain);
  2019. }
  2020. m_ovr.flip();
  2021. m_ovr.swap(_hmd); // TODO - move this out of end-of-frame
  2022. // need to swap GL render context even if OVR is enabled to get the mirror texture in the output
  2023. m_glctx.swap();
  2024. }
  2025. }
  2026. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint16_t _flags) BX_OVERRIDE
  2027. {
  2028. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  2029. }
  2030. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  2031. {
  2032. m_indexBuffers[_handle.idx].destroy();
  2033. }
  2034. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  2035. {
  2036. VertexDecl& decl = m_vertexDecls[_handle.idx];
  2037. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  2038. dump(decl);
  2039. }
  2040. void destroyVertexDecl(VertexDeclHandle /*_handle*/) BX_OVERRIDE
  2041. {
  2042. }
  2043. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint16_t _flags) BX_OVERRIDE
  2044. {
  2045. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  2046. }
  2047. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  2048. {
  2049. m_vertexBuffers[_handle.idx].destroy();
  2050. }
  2051. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  2052. {
  2053. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  2054. }
  2055. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  2056. {
  2057. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  2058. }
  2059. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  2060. {
  2061. m_indexBuffers[_handle.idx].destroy();
  2062. }
  2063. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  2064. {
  2065. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  2066. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  2067. }
  2068. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  2069. {
  2070. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  2071. }
  2072. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  2073. {
  2074. m_vertexBuffers[_handle.idx].destroy();
  2075. }
  2076. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  2077. {
  2078. m_shaders[_handle.idx].create(_mem);
  2079. }
  2080. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  2081. {
  2082. m_shaders[_handle.idx].destroy();
  2083. }
  2084. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  2085. {
  2086. ShaderGL dummyFragmentShader;
  2087. m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader);
  2088. }
  2089. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  2090. {
  2091. m_program[_handle.idx].destroy();
  2092. }
  2093. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  2094. {
  2095. m_textures[_handle.idx].create(_mem, _flags, _skip);
  2096. }
  2097. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) BX_OVERRIDE
  2098. {
  2099. }
  2100. void updateTexture(TextureHandle _handle, uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem) BX_OVERRIDE
  2101. {
  2102. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  2103. }
  2104. void updateTextureEnd() BX_OVERRIDE
  2105. {
  2106. }
  2107. void readTexture(TextureHandle _handle, void* _data) BX_OVERRIDE
  2108. {
  2109. if (m_readBackSupported)
  2110. {
  2111. const TextureGL& texture = m_textures[_handle.idx];
  2112. const bool compressed = isCompressed(TextureFormat::Enum(texture.m_textureFormat) );
  2113. GL_CHECK(glBindTexture(texture.m_target, texture.m_id) );
  2114. if (compressed)
  2115. {
  2116. GL_CHECK(glGetCompressedTexImage(texture.m_target
  2117. , 0
  2118. , _data
  2119. ) );
  2120. }
  2121. else
  2122. {
  2123. GL_CHECK(glGetTexImage(texture.m_target
  2124. , 0
  2125. , texture.m_fmt
  2126. , texture.m_type
  2127. , _data
  2128. ) );
  2129. }
  2130. GL_CHECK(glBindTexture(texture.m_target, 0) );
  2131. }
  2132. }
  2133. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height, uint8_t _numMips) BX_OVERRIDE
  2134. {
  2135. TextureGL& texture = m_textures[_handle.idx];
  2136. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  2137. const Memory* mem = alloc(size);
  2138. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  2139. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  2140. bx::write(&writer, magic);
  2141. TextureCreate tc;
  2142. tc.m_width = _width;
  2143. tc.m_height = _height;
  2144. tc.m_depth = 0;
  2145. tc.m_numLayers = 1;
  2146. tc.m_numMips = _numMips;
  2147. tc.m_format = TextureFormat::Enum(texture.m_requestedFormat);
  2148. tc.m_cubeMap = false;
  2149. tc.m_mem = NULL;
  2150. bx::write(&writer, tc);
  2151. texture.destroy();
  2152. texture.create(mem, texture.m_flags, 0);
  2153. release(mem);
  2154. }
  2155. void overrideInternal(TextureHandle _handle, uintptr_t _ptr) BX_OVERRIDE
  2156. {
  2157. m_textures[_handle.idx].overrideInternal(_ptr);
  2158. }
  2159. uintptr_t getInternal(TextureHandle _handle) BX_OVERRIDE
  2160. {
  2161. return uintptr_t(m_textures[_handle.idx].m_id);
  2162. }
  2163. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  2164. {
  2165. m_textures[_handle.idx].destroy();
  2166. }
  2167. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const Attachment* _attachment) BX_OVERRIDE
  2168. {
  2169. m_frameBuffers[_handle.idx].create(_num, _attachment);
  2170. }
  2171. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) BX_OVERRIDE
  2172. {
  2173. uint16_t denseIdx = m_numWindows++;
  2174. m_windows[denseIdx] = _handle;
  2175. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  2176. }
  2177. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  2178. {
  2179. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  2180. if (UINT16_MAX != denseIdx)
  2181. {
  2182. --m_numWindows;
  2183. if (m_numWindows > 1)
  2184. {
  2185. FrameBufferHandle handle = m_windows[m_numWindows];
  2186. m_windows[denseIdx] = handle;
  2187. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  2188. }
  2189. }
  2190. }
  2191. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  2192. {
  2193. if (NULL != m_uniforms[_handle.idx])
  2194. {
  2195. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2196. }
  2197. uint32_t size = g_uniformTypeSize[_type]*_num;
  2198. void* data = BX_ALLOC(g_allocator, size);
  2199. memset(data, 0, size);
  2200. m_uniforms[_handle.idx] = data;
  2201. m_uniformReg.add(_handle, _name, m_uniforms[_handle.idx]);
  2202. }
  2203. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  2204. {
  2205. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  2206. m_uniforms[_handle.idx] = NULL;
  2207. m_uniformReg.remove(_handle);
  2208. }
  2209. void saveScreenShot(const char* _filePath) BX_OVERRIDE
  2210. {
  2211. uint32_t length = m_resolution.m_width*m_resolution.m_height*4;
  2212. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2213. uint32_t width = m_resolution.m_width;
  2214. uint32_t height = m_resolution.m_height;
  2215. GL_CHECK(glReadPixels(0
  2216. , 0
  2217. , width
  2218. , height
  2219. , m_readPixelsFmt
  2220. , GL_UNSIGNED_BYTE
  2221. , data
  2222. ) );
  2223. if (GL_RGBA == m_readPixelsFmt)
  2224. {
  2225. imageSwizzleBgra8(width, height, width*4, data, data);
  2226. }
  2227. g_callback->screenShot(_filePath
  2228. , width
  2229. , height
  2230. , width*4
  2231. , data
  2232. , length
  2233. , true
  2234. );
  2235. BX_FREE(g_allocator, data);
  2236. }
  2237. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  2238. {
  2239. bx::strlcpy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  2240. , _name
  2241. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  2242. );
  2243. }
  2244. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  2245. {
  2246. memcpy(m_uniforms[_loc], _data, _size);
  2247. }
  2248. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  2249. {
  2250. GL_CHECK(glInsertEventMarker(_size, _marker) );
  2251. }
  2252. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  2253. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  2254. {
  2255. if (0 != m_vao)
  2256. {
  2257. GL_CHECK(glBindVertexArray(m_vao) );
  2258. }
  2259. uint32_t width = m_resolution.m_width;
  2260. uint32_t height = m_resolution.m_height;
  2261. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2262. GL_CHECK(glViewport(0, 0, width, height) );
  2263. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2264. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2265. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2266. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2267. GL_CHECK(glDisable(GL_CULL_FACE) );
  2268. GL_CHECK(glDisable(GL_BLEND) );
  2269. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2270. ProgramGL& program = m_program[_blitter.m_program.idx];
  2271. GL_CHECK(glUseProgram(program.m_id) );
  2272. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  2273. float proj[16];
  2274. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  2275. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  2276. , 1
  2277. , GL_FALSE
  2278. , proj
  2279. ) );
  2280. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  2281. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) );
  2282. if (!BX_ENABLED(BX_PLATFORM_OSX) )
  2283. {
  2284. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2285. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2286. {
  2287. if (m_samplerObjectSupport)
  2288. {
  2289. GL_CHECK(glBindSampler(0, 0) );
  2290. }
  2291. }
  2292. }
  2293. }
  2294. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  2295. {
  2296. const uint32_t numVertices = _numIndices*4/6;
  2297. if (0 < numVertices)
  2298. {
  2299. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data);
  2300. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data);
  2301. VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  2302. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2303. IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  2304. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  2305. ProgramGL& program = m_program[_blitter.m_program.idx];
  2306. program.bindAttributes(_blitter.m_decl, 0);
  2307. GL_CHECK(glDrawElements(GL_TRIANGLES
  2308. , _numIndices
  2309. , GL_UNSIGNED_SHORT
  2310. , (void*)0
  2311. ) );
  2312. }
  2313. }
  2314. void updateResolution(const Resolution& _resolution)
  2315. {
  2316. bool recenter = !!(_resolution.m_flags & BGFX_RESET_HMD_RECENTER);
  2317. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  2318. ? m_maxAnisotropyDefault
  2319. : 0.0f
  2320. ;
  2321. if (s_extension[Extension::ARB_depth_clamp].m_supported)
  2322. {
  2323. if (!!(_resolution.m_flags & BGFX_RESET_DEPTH_CLAMP) )
  2324. {
  2325. GL_CHECK(glEnable(GL_DEPTH_CLAMP) );
  2326. }
  2327. else
  2328. {
  2329. GL_CHECK(glDisable(GL_DEPTH_CLAMP) );
  2330. }
  2331. }
  2332. const uint32_t maskFlags = ~(0
  2333. | BGFX_RESET_HMD_RECENTER
  2334. | BGFX_RESET_MAXANISOTROPY
  2335. | BGFX_RESET_DEPTH_CLAMP
  2336. | BGFX_RESET_SUSPEND
  2337. );
  2338. if (m_resolution.m_width != _resolution.m_width
  2339. || m_resolution.m_height != _resolution.m_height
  2340. || (m_resolution.m_flags&maskFlags) != (_resolution.m_flags&maskFlags) )
  2341. {
  2342. uint32_t flags = _resolution.m_flags & (~BGFX_RESET_INTERNAL_FORCE);
  2343. m_resolution = _resolution;
  2344. m_resolution.m_flags = flags;
  2345. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  2346. m_textVideoMem.clear();
  2347. if ( (flags & BGFX_RESET_HMD)
  2348. && m_ovr.isInitialized() )
  2349. {
  2350. flags &= ~BGFX_RESET_MSAA_MASK;
  2351. }
  2352. setRenderContextSize(m_resolution.m_width
  2353. , m_resolution.m_height
  2354. , flags
  2355. );
  2356. updateCapture();
  2357. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  2358. {
  2359. m_frameBuffers[ii].postReset();
  2360. }
  2361. ovrPreReset();
  2362. ovrPostReset();
  2363. }
  2364. if (recenter)
  2365. {
  2366. m_ovr.recenter();
  2367. }
  2368. }
  2369. void setShaderUniform4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2370. {
  2371. GL_CHECK(glUniform4fv(_regIndex
  2372. , _numRegs
  2373. , (const GLfloat*)_val
  2374. ) );
  2375. }
  2376. void setShaderUniform4x4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  2377. {
  2378. GL_CHECK(glUniformMatrix4fv(_regIndex
  2379. , _numRegs
  2380. , GL_FALSE
  2381. , (const GLfloat*)_val
  2382. ) );
  2383. }
  2384. uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint16_t _discard = BGFX_CLEAR_NONE, bool _msaa = true)
  2385. {
  2386. if (isValid(m_fbh)
  2387. && m_fbh.idx != _fbh.idx)
  2388. {
  2389. FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2390. frameBuffer.resolve();
  2391. if (BGFX_CLEAR_NONE != m_fbDiscard)
  2392. {
  2393. frameBuffer.discard(m_fbDiscard);
  2394. m_fbDiscard = BGFX_CLEAR_NONE;
  2395. }
  2396. }
  2397. m_glctx.makeCurrent(NULL);
  2398. if (!isValid(_fbh) )
  2399. {
  2400. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2401. if (m_srgbWriteControlSupport)
  2402. {
  2403. if (0 != (m_resolution.m_flags & BGFX_RESET_SRGB_BACKBUFFER) )
  2404. {
  2405. GL_CHECK(glEnable(GL_FRAMEBUFFER_SRGB) );
  2406. }
  2407. else
  2408. {
  2409. GL_CHECK(glDisable(GL_FRAMEBUFFER_SRGB) );
  2410. }
  2411. }
  2412. }
  2413. else
  2414. {
  2415. FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx];
  2416. _height = frameBuffer.m_height;
  2417. if (UINT16_MAX != frameBuffer.m_denseIdx)
  2418. {
  2419. m_glctx.makeCurrent(frameBuffer.m_swapChain);
  2420. }
  2421. else
  2422. {
  2423. m_glctx.makeCurrent(NULL);
  2424. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer.m_fbo[0]) );
  2425. }
  2426. }
  2427. m_fbh = _fbh;
  2428. m_fbDiscard = _discard;
  2429. m_rtMsaa = _msaa;
  2430. return _height;
  2431. }
  2432. uint32_t getNumRt() const
  2433. {
  2434. if (isValid(m_fbh) )
  2435. {
  2436. const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  2437. return frameBuffer.m_num;
  2438. }
  2439. return 1;
  2440. }
  2441. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  2442. {
  2443. if (0 == m_msaaBackBufferFbo // iOS
  2444. && 1 < _msaa)
  2445. {
  2446. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  2447. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2448. GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2449. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2450. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  2451. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2452. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  2453. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  2454. GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2455. ? GL_DEPTH_STENCIL_ATTACHMENT
  2456. : GL_DEPTH_ATTACHMENT
  2457. ;
  2458. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  2459. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2460. , "glCheckFramebufferStatus failed 0x%08x"
  2461. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  2462. );
  2463. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2464. }
  2465. }
  2466. void destroyMsaaFbo()
  2467. {
  2468. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2469. && 0 != m_msaaBackBufferFbo)
  2470. {
  2471. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  2472. m_msaaBackBufferFbo = 0;
  2473. if (0 != m_msaaBackBufferRbos[0])
  2474. {
  2475. GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2476. m_msaaBackBufferRbos[0] = 0;
  2477. m_msaaBackBufferRbos[1] = 0;
  2478. }
  2479. }
  2480. }
  2481. void blitMsaaFbo()
  2482. {
  2483. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2484. && 0 != m_msaaBackBufferFbo)
  2485. {
  2486. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2487. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2488. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2489. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  2490. uint32_t width = m_resolution.m_width;
  2491. uint32_t height = m_resolution.m_height;
  2492. GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  2493. ? GL_NEAREST
  2494. : GL_LINEAR
  2495. ;
  2496. GL_CHECK(glBlitFramebuffer(0
  2497. , 0
  2498. , width
  2499. , height
  2500. , 0
  2501. , 0
  2502. , width
  2503. , height
  2504. , GL_COLOR_BUFFER_BIT
  2505. , filter
  2506. ) );
  2507. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2508. }
  2509. }
  2510. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _flags = 0)
  2511. {
  2512. if (_width != 0
  2513. || _height != 0)
  2514. {
  2515. if (!m_glctx.isValid() )
  2516. {
  2517. m_glctx.create(_width, _height);
  2518. #if BX_PLATFORM_IOS
  2519. // iOS: need to figure out how to deal with FBO created by context.
  2520. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo();
  2521. #endif // BX_PLATFORM_IOS
  2522. }
  2523. else
  2524. {
  2525. destroyMsaaFbo();
  2526. m_glctx.resize(_width, _height, _flags);
  2527. uint32_t msaa = (_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  2528. msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  2529. createMsaaFbo(_width, _height, msaa);
  2530. }
  2531. }
  2532. m_flip = true;
  2533. }
  2534. void invalidateCache()
  2535. {
  2536. if (m_vaoSupport)
  2537. {
  2538. m_vaoStateCache.invalidate();
  2539. }
  2540. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2541. && m_samplerObjectSupport)
  2542. {
  2543. m_samplerStateCache.invalidate();
  2544. }
  2545. }
  2546. void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags, const float _rgba[4])
  2547. {
  2548. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2549. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2550. {
  2551. if (0 == (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags) )
  2552. {
  2553. const uint32_t index = (_flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  2554. _flags &= ~BGFX_TEXTURE_RESERVED_MASK;
  2555. _flags &= BGFX_TEXTURE_SAMPLER_BITS_MASK;
  2556. _flags |= _numMips<<BGFX_TEXTURE_RESERVED_SHIFT;
  2557. GLuint sampler;
  2558. bool hasBorderColor = false;
  2559. bx::HashMurmur2A murmur;
  2560. uint32_t hash;
  2561. murmur.begin();
  2562. murmur.add(_flags);
  2563. if (!needBorderColor(_flags) )
  2564. {
  2565. murmur.add(-1);
  2566. hash = murmur.end();
  2567. sampler = m_samplerStateCache.find(hash);
  2568. }
  2569. else
  2570. {
  2571. murmur.add(index);
  2572. hash = murmur.end();
  2573. if (NULL != _rgba)
  2574. {
  2575. hasBorderColor = true;
  2576. sampler = UINT32_MAX;
  2577. }
  2578. else
  2579. {
  2580. sampler = m_samplerStateCache.find(hash);
  2581. }
  2582. }
  2583. if (UINT32_MAX == sampler)
  2584. {
  2585. sampler = m_samplerStateCache.add(hash);
  2586. GL_CHECK(glSamplerParameteri(sampler
  2587. , GL_TEXTURE_WRAP_S
  2588. , s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]
  2589. ) );
  2590. GL_CHECK(glSamplerParameteri(sampler
  2591. , GL_TEXTURE_WRAP_T
  2592. , s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]
  2593. ) );
  2594. GL_CHECK(glSamplerParameteri(sampler
  2595. , GL_TEXTURE_WRAP_R
  2596. , s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]
  2597. ) );
  2598. GLenum minFilter;
  2599. GLenum magFilter;
  2600. getFilters(_flags, 1 < _numMips, magFilter, minFilter);
  2601. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) );
  2602. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) );
  2603. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2604. || m_borderColorSupport)
  2605. {
  2606. if (hasBorderColor)
  2607. {
  2608. GL_CHECK(glSamplerParameterfv(sampler, GL_TEXTURE_BORDER_COLOR, _rgba) );
  2609. }
  2610. }
  2611. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  2612. && 0.0f < m_maxAnisotropy)
  2613. {
  2614. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) );
  2615. }
  2616. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2617. || m_shadowSamplersSupport)
  2618. {
  2619. const uint32_t cmpFunc = (_flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  2620. if (0 == cmpFunc)
  2621. {
  2622. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  2623. }
  2624. else
  2625. {
  2626. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  2627. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  2628. }
  2629. }
  2630. }
  2631. GL_CHECK(glBindSampler(_stage, sampler) );
  2632. }
  2633. else
  2634. {
  2635. GL_CHECK(glBindSampler(_stage, 0) );
  2636. }
  2637. }
  2638. }
  2639. bool isVisible(Frame* _render, OcclusionQueryHandle _handle, bool _visible)
  2640. {
  2641. m_occlusionQuery.resolve(_render);
  2642. return _visible == (0 != _render->m_occlusion[_handle.idx]);
  2643. }
  2644. void ovrPostReset()
  2645. {
  2646. #if BGFX_CONFIG_USE_OVR
  2647. if (m_resolution.m_flags & (BGFX_RESET_HMD|BGFX_RESET_HMD_DEBUG) )
  2648. {
  2649. const uint32_t msaaSamples = 1 << ( (m_resolution.m_flags&BGFX_RESET_MSAA_MASK) >> BGFX_RESET_MSAA_SHIFT);
  2650. m_ovr.postReset(msaaSamples, m_resolution.m_width, m_resolution.m_height);
  2651. }
  2652. #endif // BGFX_CONFIG_USE_OVR
  2653. }
  2654. void ovrPreReset()
  2655. {
  2656. #if BGFX_CONFIG_USE_OVR
  2657. m_ovr.preReset();
  2658. #endif // BGFX_CONFIG_USE_OVR
  2659. }
  2660. void updateCapture()
  2661. {
  2662. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  2663. {
  2664. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  2665. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  2666. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  2667. }
  2668. else
  2669. {
  2670. captureFinish();
  2671. }
  2672. }
  2673. void capture()
  2674. {
  2675. if (NULL != m_capture)
  2676. {
  2677. GL_CHECK(glReadPixels(0
  2678. , 0
  2679. , m_resolution.m_width
  2680. , m_resolution.m_height
  2681. , m_readPixelsFmt
  2682. , GL_UNSIGNED_BYTE
  2683. , m_capture
  2684. ) );
  2685. if (GL_RGBA == m_readPixelsFmt)
  2686. {
  2687. imageSwizzleBgra8(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, m_capture, m_capture);
  2688. }
  2689. g_callback->captureFrame(m_capture, m_captureSize);
  2690. }
  2691. }
  2692. void captureFinish()
  2693. {
  2694. if (NULL != m_capture)
  2695. {
  2696. g_callback->captureEnd();
  2697. BX_FREE(g_allocator, m_capture);
  2698. m_capture = NULL;
  2699. m_captureSize = 0;
  2700. }
  2701. }
  2702. bool programFetchFromCache(GLuint programId, uint64_t _id)
  2703. {
  2704. _id ^= m_hash;
  2705. bool cached = false;
  2706. if (m_programBinarySupport)
  2707. {
  2708. uint32_t length = g_callback->cacheReadSize(_id);
  2709. cached = length > 0;
  2710. if (cached)
  2711. {
  2712. void* data = BX_ALLOC(g_allocator, length);
  2713. if (g_callback->cacheRead(_id, data, length) )
  2714. {
  2715. bx::MemoryReader reader(data, length);
  2716. GLenum format;
  2717. bx::read(&reader, format);
  2718. GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  2719. }
  2720. BX_FREE(g_allocator, data);
  2721. }
  2722. #if BGFX_CONFIG_RENDERER_OPENGL
  2723. GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  2724. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2725. }
  2726. return cached;
  2727. }
  2728. void programCache(GLuint programId, uint64_t _id)
  2729. {
  2730. _id ^= m_hash;
  2731. if (m_programBinarySupport)
  2732. {
  2733. GLint programLength;
  2734. GLenum format;
  2735. GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  2736. if (0 < programLength)
  2737. {
  2738. uint32_t length = programLength + 4;
  2739. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2740. GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) );
  2741. *(uint32_t*)data = format;
  2742. g_callback->cacheWrite(_id, data, length);
  2743. BX_FREE(g_allocator, data);
  2744. }
  2745. }
  2746. }
  2747. void commit(UniformBuffer& _uniformBuffer)
  2748. {
  2749. _uniformBuffer.reset();
  2750. for (;;)
  2751. {
  2752. uint32_t opcode = _uniformBuffer.read();
  2753. if (UniformType::End == opcode)
  2754. {
  2755. break;
  2756. }
  2757. UniformType::Enum type;
  2758. uint16_t ignore;
  2759. uint16_t num;
  2760. uint16_t copy;
  2761. UniformBuffer::decodeOpcode(opcode, type, ignore, num, copy);
  2762. const char* data;
  2763. if (copy)
  2764. {
  2765. data = _uniformBuffer.read(g_uniformTypeSize[type]*num);
  2766. }
  2767. else
  2768. {
  2769. UniformHandle handle;
  2770. memcpy(&handle, _uniformBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  2771. data = (const char*)m_uniforms[handle.idx];
  2772. }
  2773. uint32_t loc = _uniformBuffer.read();
  2774. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  2775. case UniformType::_uniform: \
  2776. { \
  2777. _type* value = (_type*)data; \
  2778. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  2779. } \
  2780. break;
  2781. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  2782. case UniformType::_uniform: \
  2783. { \
  2784. _type* value = (_type*)data; \
  2785. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  2786. } \
  2787. break;
  2788. switch (type)
  2789. {
  2790. // case ConstantType::Int1:
  2791. // {
  2792. // int* value = (int*)data;
  2793. // BX_TRACE("Int1 sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  2794. // GL_CHECK(glUniform1iv(loc, num, value) );
  2795. // }
  2796. // break;
  2797. CASE_IMPLEMENT_UNIFORM(Int1, 1iv, I, int);
  2798. CASE_IMPLEMENT_UNIFORM(Vec4, 4fv, F, float);
  2799. CASE_IMPLEMENT_UNIFORM_T(Mat3, Matrix3fv, F, float);
  2800. CASE_IMPLEMENT_UNIFORM_T(Mat4, Matrix4fv, F, float);
  2801. case UniformType::End:
  2802. break;
  2803. default:
  2804. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _uniformBuffer.getPos(), opcode, type, loc, num, copy);
  2805. break;
  2806. }
  2807. #undef CASE_IMPLEMENT_UNIFORM
  2808. #undef CASE_IMPLEMENT_UNIFORM_T
  2809. }
  2810. }
  2811. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4])
  2812. {
  2813. uint32_t numMrt = 1;
  2814. FrameBufferHandle fbh = m_fbh;
  2815. if (isValid(fbh) )
  2816. {
  2817. const FrameBufferGL& fb = m_frameBuffers[fbh.idx];
  2818. numMrt = bx::uint32_max(1, fb.m_num);
  2819. }
  2820. if (1 == numMrt)
  2821. {
  2822. GLuint flags = 0;
  2823. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  2824. {
  2825. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2826. {
  2827. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[0]);
  2828. const float* rgba = _palette[index];
  2829. const float rr = rgba[0];
  2830. const float gg = rgba[1];
  2831. const float bb = rgba[2];
  2832. const float aa = rgba[3];
  2833. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2834. }
  2835. else
  2836. {
  2837. float rr = _clear.m_index[0]*1.0f/255.0f;
  2838. float gg = _clear.m_index[1]*1.0f/255.0f;
  2839. float bb = _clear.m_index[2]*1.0f/255.0f;
  2840. float aa = _clear.m_index[3]*1.0f/255.0f;
  2841. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2842. }
  2843. flags |= GL_COLOR_BUFFER_BIT;
  2844. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2845. }
  2846. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2847. {
  2848. flags |= GL_DEPTH_BUFFER_BIT;
  2849. GL_CHECK(glClearDepth(_clear.m_depth) );
  2850. GL_CHECK(glDepthMask(GL_TRUE) );
  2851. }
  2852. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2853. {
  2854. flags |= GL_STENCIL_BUFFER_BIT;
  2855. GL_CHECK(glClearStencil(_clear.m_stencil) );
  2856. }
  2857. if (0 != flags)
  2858. {
  2859. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  2860. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  2861. GL_CHECK(glClear(flags) );
  2862. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2863. }
  2864. }
  2865. else
  2866. {
  2867. const GLuint defaultVao = m_vao;
  2868. if (0 != defaultVao)
  2869. {
  2870. GL_CHECK(glBindVertexArray(defaultVao) );
  2871. }
  2872. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2873. GL_CHECK(glDisable(GL_CULL_FACE) );
  2874. GL_CHECK(glDisable(GL_BLEND) );
  2875. GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags);
  2876. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  2877. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2878. {
  2879. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2880. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2881. GL_CHECK(glDepthMask(GL_TRUE) );
  2882. }
  2883. else
  2884. {
  2885. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2886. }
  2887. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2888. {
  2889. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2890. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  2891. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  2892. }
  2893. else
  2894. {
  2895. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2896. }
  2897. VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  2898. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  2899. {
  2900. struct Vertex
  2901. {
  2902. float m_x;
  2903. float m_y;
  2904. float m_z;
  2905. };
  2906. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  2907. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  2908. const float depth = _clear.m_depth * 2.0f - 1.0f;
  2909. vertex->m_x = -1.0f;
  2910. vertex->m_y = -1.0f;
  2911. vertex->m_z = depth;
  2912. vertex++;
  2913. vertex->m_x = 1.0f;
  2914. vertex->m_y = -1.0f;
  2915. vertex->m_z = depth;
  2916. vertex++;
  2917. vertex->m_x = -1.0f;
  2918. vertex->m_y = 1.0f;
  2919. vertex->m_z = depth;
  2920. vertex++;
  2921. vertex->m_x = 1.0f;
  2922. vertex->m_y = 1.0f;
  2923. vertex->m_z = depth;
  2924. }
  2925. vb.update(0, 4*_clearQuad.m_decl.m_stride, _clearQuad.m_vb->data);
  2926. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2927. ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  2928. GL_CHECK(glUseProgram(program.m_id) );
  2929. program.bindAttributes(vertexDecl, 0);
  2930. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  2931. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2932. {
  2933. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2934. {
  2935. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_COLOR_PALETTE-1, _clear.m_index[ii]);
  2936. memcpy(mrtClear[ii], _palette[index], 16);
  2937. }
  2938. }
  2939. else
  2940. {
  2941. float rgba[4] =
  2942. {
  2943. _clear.m_index[0] * 1.0f / 255.0f,
  2944. _clear.m_index[1] * 1.0f / 255.0f,
  2945. _clear.m_index[2] * 1.0f / 255.0f,
  2946. _clear.m_index[3] * 1.0f / 255.0f,
  2947. };
  2948. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2949. {
  2950. memcpy(mrtClear[ii], rgba, 16);
  2951. }
  2952. }
  2953. GL_CHECK(glUniform4fv(0, numMrt, mrtClear[0]) );
  2954. GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP
  2955. , 0
  2956. , 4
  2957. ) );
  2958. }
  2959. }
  2960. void* m_renderdocdll;
  2961. uint16_t m_numWindows;
  2962. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2963. IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  2964. VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  2965. ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS];
  2966. ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS];
  2967. TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES];
  2968. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  2969. FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2970. UniformRegistry m_uniformReg;
  2971. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  2972. TimerQueryGL m_gpuTimer;
  2973. OcclusionQueryGL m_occlusionQuery;
  2974. VaoStateCache m_vaoStateCache;
  2975. SamplerStateCache m_samplerStateCache;
  2976. TextVideoMem m_textVideoMem;
  2977. bool m_rtMsaa;
  2978. FrameBufferHandle m_fbh;
  2979. uint16_t m_fbDiscard;
  2980. Resolution m_resolution;
  2981. void* m_capture;
  2982. uint32_t m_captureSize;
  2983. float m_maxAnisotropy;
  2984. float m_maxAnisotropyDefault;
  2985. int32_t m_maxMsaa;
  2986. GLuint m_vao;
  2987. bool m_blitSupported;
  2988. bool m_readBackSupported;
  2989. bool m_vaoSupport;
  2990. bool m_samplerObjectSupport;
  2991. bool m_shadowSamplersSupport;
  2992. bool m_srgbWriteControlSupport;
  2993. bool m_borderColorSupport;
  2994. bool m_programBinarySupport;
  2995. bool m_textureSwizzleSupport;
  2996. bool m_depthTextureSupport;
  2997. bool m_timerQuerySupport;
  2998. bool m_occlusionQuerySupport;
  2999. bool m_atocSupport;
  3000. bool m_conservativeRasterSupport;
  3001. bool m_flip;
  3002. uint64_t m_hash;
  3003. GLenum m_readPixelsFmt;
  3004. GLuint m_backBufferFbo;
  3005. GLuint m_msaaBackBufferFbo;
  3006. GLuint m_msaaBackBufferRbos[2];
  3007. GlContext m_glctx;
  3008. const char* m_vendor;
  3009. const char* m_renderer;
  3010. const char* m_version;
  3011. const char* m_glslVersion;
  3012. VR m_ovr;
  3013. #if BGFX_CONFIG_USE_OVR
  3014. VRImplOVRGL m_ovrRender;
  3015. #endif // BGFX_CONFIG_USE_OVR
  3016. };
  3017. RendererContextGL* s_renderGL;
  3018. RendererContextI* rendererCreate()
  3019. {
  3020. s_renderGL = BX_NEW(g_allocator, RendererContextGL);
  3021. s_renderGL->init();
  3022. return s_renderGL;
  3023. }
  3024. void rendererDestroy()
  3025. {
  3026. s_renderGL->shutdown();
  3027. BX_DELETE(g_allocator, s_renderGL);
  3028. s_renderGL = NULL;
  3029. }
  3030. #if BGFX_CONFIG_USE_OVR
  3031. VRImplOVRGL::VRImplOVRGL()
  3032. : m_mirrorTexture(NULL)
  3033. {
  3034. memset(&m_textureSwapChain, 0, sizeof(m_textureSwapChain) );
  3035. }
  3036. static void setDefaultSamplerState()
  3037. {
  3038. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
  3039. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
  3040. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
  3041. GL_CHECK(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
  3042. }
  3043. bool VRImplOVRGL::createSwapChain(const VRDesc& _desc, int _msaaSamples, int _mirrorWidth, int _mirrorHeight)
  3044. {
  3045. for (int eye = 0; eye < 2; ++eye)
  3046. {
  3047. if (NULL == m_textureSwapChain[eye])
  3048. {
  3049. m_eyeFbo[eye] = 0;
  3050. m_depthBuffer[eye] = 0;
  3051. m_msaaEyeFbo[eye] = 0;
  3052. m_msaaEyeTexId[eye] = 0;
  3053. m_msaaDepthBuffer[eye] = 0;
  3054. memset(&m_eyeTexId[eye], 0, sizeof(m_eyeTexId[eye]) );
  3055. ovrTextureSwapChainDesc swapchainDesc = {};
  3056. swapchainDesc.Type = ovrTexture_2D;
  3057. swapchainDesc.ArraySize = 1;
  3058. swapchainDesc.Width = _desc.m_eyeSize[eye].m_w;
  3059. swapchainDesc.Height = _desc.m_eyeSize[eye].m_h;
  3060. swapchainDesc.MipLevels = 1;
  3061. swapchainDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
  3062. swapchainDesc.SampleCount = 1;
  3063. swapchainDesc.StaticImage = ovrFalse;
  3064. ovrResult result = ovr_CreateTextureSwapChainGL(m_session, &swapchainDesc, &m_textureSwapChain[eye]);
  3065. if (!OVR_SUCCESS(result) )
  3066. {
  3067. destroySwapChain();
  3068. return false;
  3069. }
  3070. int textureCount = 0;
  3071. ovr_GetTextureSwapChainLength(m_session, m_textureSwapChain[eye], &textureCount);
  3072. for (int ii = 0; ii < textureCount; ++ii)
  3073. {
  3074. ovr_GetTextureSwapChainBufferGL(m_session, m_textureSwapChain[eye], ii, &m_eyeTexId[eye][ii]);
  3075. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_eyeTexId[eye][ii]) );
  3076. setDefaultSamplerState();
  3077. }
  3078. GL_CHECK(glGenFramebuffers(1, &m_eyeFbo[eye]) );
  3079. // create depth buffer
  3080. GL_CHECK(glGenTextures(1, &m_depthBuffer[eye]) );
  3081. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_depthBuffer[eye]) );
  3082. setDefaultSamplerState();
  3083. GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, _desc.m_eyeSize[eye].m_w, _desc.m_eyeSize[eye].m_h, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL) );
  3084. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_eyeFbo[eye]) );
  3085. GL_CHECK(glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthBuffer[eye], 0) );
  3086. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3087. // create MSAA targets if needed
  3088. if (_msaaSamples > 1)
  3089. {
  3090. GL_CHECK(glGenFramebuffers(1, &m_msaaEyeFbo[eye]) );
  3091. // create color MSAA texture
  3092. GL_CHECK(glGenTextures(1, &m_msaaEyeTexId[eye]) );
  3093. GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_msaaEyeTexId[eye]) );
  3094. GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, _msaaSamples, GL_RGBA, _desc.m_eyeSize[eye].m_w, _desc.m_eyeSize[eye].m_h, false) );
  3095. setDefaultSamplerState();
  3096. // create MSAA depth buffer
  3097. GL_CHECK(glGenTextures(1, &m_msaaDepthBuffer[eye]) );
  3098. GL_CHECK(glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_depthBuffer[eye]) );
  3099. GL_CHECK(glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, _msaaSamples, GL_DEPTH_COMPONENT, _desc.m_eyeSize[eye].m_w, _desc.m_eyeSize[eye].m_h, false) );
  3100. setDefaultSamplerState();
  3101. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaEyeFbo[eye]) );
  3102. GL_CHECK(glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, m_msaaEyeTexId[eye], 0) );
  3103. GL_CHECK(glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0) );
  3104. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3105. }
  3106. m_renderLayer.ColorTexture[eye] = m_textureSwapChain[eye];
  3107. }
  3108. }
  3109. m_renderLayer.Header.Flags |= ovrLayerFlag_TextureOriginAtBottomLeft;
  3110. if (NULL == m_mirrorTexture)
  3111. {
  3112. m_mirrorFbo = 0;
  3113. ovrMirrorTextureDesc mirrorDesc = {};
  3114. mirrorDesc.Width = _mirrorWidth;
  3115. mirrorDesc.Height = _mirrorHeight;
  3116. mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
  3117. // Fallback to doing nothing if mirror was not created. This is to prevent errors with fast window resizes
  3118. ovr_CreateMirrorTextureGL(m_session, &mirrorDesc, &m_mirrorTexture);
  3119. if (m_mirrorTexture)
  3120. {
  3121. m_mirrorWidth = _mirrorWidth;
  3122. m_mirrorHeight = _mirrorHeight;
  3123. // Configure the mirror read buffer
  3124. GLuint texId;
  3125. ovr_GetMirrorTextureBufferGL(m_session, m_mirrorTexture, &texId);
  3126. GL_CHECK(glGenFramebuffers(1, &m_mirrorFbo) );
  3127. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_mirrorFbo) );
  3128. GL_CHECK(glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texId, 0) );
  3129. GL_CHECK(glFramebufferRenderbuffer(GL_READ_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0) );
  3130. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3131. if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  3132. {
  3133. GL_CHECK(glDeleteFramebuffers(1, &m_mirrorFbo) );
  3134. ovr_DestroyMirrorTexture(m_session, m_mirrorTexture);
  3135. m_mirrorTexture = NULL;
  3136. BX_CHECK(false, "Could not initialize VR mirror buffers!");
  3137. }
  3138. }
  3139. }
  3140. return true;
  3141. }
  3142. void VRImplOVRGL::destroySwapChain()
  3143. {
  3144. for (int eye = 0; eye < 2; ++eye)
  3145. {
  3146. if (NULL != m_textureSwapChain[eye])
  3147. {
  3148. GL_CHECK(glDeleteFramebuffers(1, &m_eyeFbo[eye]) );
  3149. GL_CHECK(glDeleteTextures(1, &m_depthBuffer[eye]) );
  3150. ovr_DestroyTextureSwapChain(m_session, m_textureSwapChain[eye]);
  3151. m_textureSwapChain[eye] = NULL;
  3152. if (0 != m_msaaEyeFbo[eye])
  3153. {
  3154. GL_CHECK(glDeleteFramebuffers(1, &m_msaaEyeFbo[eye]) );
  3155. GL_CHECK(glDeleteTextures(1, &m_msaaEyeTexId[eye]) );
  3156. GL_CHECK(glDeleteTextures(1, &m_msaaDepthBuffer[eye]) );
  3157. m_msaaEyeFbo[eye] = 0;
  3158. }
  3159. }
  3160. }
  3161. destroyMirror();
  3162. }
  3163. void VRImplOVRGL::destroyMirror()
  3164. {
  3165. if (NULL != m_mirrorTexture)
  3166. {
  3167. GL_CHECK(glDeleteFramebuffers(1, &m_mirrorFbo) );
  3168. ovr_DestroyMirrorTexture(m_session, m_mirrorTexture);
  3169. m_mirrorTexture = NULL;
  3170. }
  3171. }
  3172. void VRImplOVRGL::renderEyeStart(const VRDesc& _desc, uint8_t _eye)
  3173. {
  3174. // set the current eye texture in the swap chain
  3175. if (0 != m_msaaEyeFbo[_eye])
  3176. {
  3177. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaEyeFbo[_eye]) );
  3178. }
  3179. else
  3180. {
  3181. int texIndex;
  3182. ovr_GetTextureSwapChainCurrentIndex(m_session, m_textureSwapChain[_eye], &texIndex);
  3183. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_eyeFbo[_eye]) );
  3184. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_eyeTexId[_eye][texIndex], 0) );
  3185. }
  3186. GL_CHECK(glViewport(0, 0, _desc.m_eyeSize[_eye].m_w, _desc.m_eyeSize[_eye].m_h) );
  3187. GL_CHECK(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) );
  3188. }
  3189. bool VRImplOVRGL::submitSwapChain(const VRDesc& _desc)
  3190. {
  3191. for (int eye = 0; eye < 2; ++eye)
  3192. {
  3193. if (0 != m_msaaEyeFbo[eye])
  3194. {
  3195. // blit the contents of MSAA FBO to the regulare eye buffer "connected" to the HMD
  3196. int destIndex;
  3197. ovr_GetTextureSwapChainCurrentIndex(m_session, m_textureSwapChain[eye], &destIndex);
  3198. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaEyeFbo[eye]) );
  3199. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_READ_FRAMEBUFFER)
  3200. , "glCheckFramebufferStatus failed 0x%08x"
  3201. , glCheckFramebufferStatus(GL_READ_FRAMEBUFFER)
  3202. );
  3203. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_eyeFbo[eye]) );
  3204. GL_CHECK(glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_eyeTexId[eye][destIndex], 0) );
  3205. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)
  3206. , "glCheckFramebufferStatus failed 0x%08x"
  3207. , glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER)
  3208. );
  3209. GL_CHECK(glBlitFramebuffer(0, 0, _desc.m_eyeSize[eye].m_w, _desc.m_eyeSize[eye].m_h, 0, 0, _desc.m_eyeSize[eye].m_w, _desc.m_eyeSize[eye].m_h, GL_COLOR_BUFFER_BIT, GL_NEAREST) );
  3210. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3211. }
  3212. ovrResult result = ovr_CommitTextureSwapChain(m_session, m_textureSwapChain[eye]);
  3213. if (!OVR_SUCCESS(result) )
  3214. {
  3215. return false;
  3216. }
  3217. }
  3218. ovrLayerHeader* layerList = &m_renderLayer.Header;
  3219. ovrResult result = ovr_SubmitFrame(m_session, 0, &m_viewScale, &layerList, 1);
  3220. if (!OVR_SUCCESS(result) )
  3221. {
  3222. return false;
  3223. }
  3224. if (result != ovrSuccess_NotVisible && NULL != m_mirrorTexture)
  3225. {
  3226. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_mirrorFbo) );
  3227. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  3228. GL_CHECK(glBlitFramebuffer(0, m_mirrorHeight, m_mirrorWidth, 0, 0, 0, m_mirrorWidth, m_mirrorHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST) );
  3229. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, 0) );
  3230. }
  3231. return true;
  3232. }
  3233. #endif // BGFX_CONFIG_USE_OVR
  3234. const char* glslTypeName(GLuint _type)
  3235. {
  3236. #define GLSL_TYPE(_ty) case _ty: return #_ty
  3237. switch (_type)
  3238. {
  3239. GLSL_TYPE(GL_INT);
  3240. GLSL_TYPE(GL_INT_VEC2);
  3241. GLSL_TYPE(GL_INT_VEC3);
  3242. GLSL_TYPE(GL_INT_VEC4);
  3243. GLSL_TYPE(GL_UNSIGNED_INT);
  3244. GLSL_TYPE(GL_UNSIGNED_INT_VEC2);
  3245. GLSL_TYPE(GL_UNSIGNED_INT_VEC3);
  3246. GLSL_TYPE(GL_UNSIGNED_INT_VEC4);
  3247. GLSL_TYPE(GL_FLOAT);
  3248. GLSL_TYPE(GL_FLOAT_VEC2);
  3249. GLSL_TYPE(GL_FLOAT_VEC3);
  3250. GLSL_TYPE(GL_FLOAT_VEC4);
  3251. GLSL_TYPE(GL_FLOAT_MAT2);
  3252. GLSL_TYPE(GL_FLOAT_MAT3);
  3253. GLSL_TYPE(GL_FLOAT_MAT4);
  3254. GLSL_TYPE(GL_SAMPLER_2D);
  3255. GLSL_TYPE(GL_SAMPLER_2D_ARRAY);
  3256. GLSL_TYPE(GL_SAMPLER_2D_MULTISAMPLE);
  3257. GLSL_TYPE(GL_INT_SAMPLER_2D);
  3258. GLSL_TYPE(GL_INT_SAMPLER_2D_ARRAY);
  3259. GLSL_TYPE(GL_INT_SAMPLER_2D_MULTISAMPLE);
  3260. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D);
  3261. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_ARRAY);
  3262. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE);
  3263. GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  3264. GLSL_TYPE(GL_SAMPLER_2D_ARRAY_SHADOW);
  3265. GLSL_TYPE(GL_SAMPLER_3D);
  3266. GLSL_TYPE(GL_INT_SAMPLER_3D);
  3267. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D);
  3268. GLSL_TYPE(GL_SAMPLER_CUBE);
  3269. GLSL_TYPE(GL_INT_SAMPLER_CUBE);
  3270. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE);
  3271. GLSL_TYPE(GL_IMAGE_1D);
  3272. GLSL_TYPE(GL_INT_IMAGE_1D);
  3273. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D);
  3274. GLSL_TYPE(GL_IMAGE_2D);
  3275. GLSL_TYPE(GL_IMAGE_2D_ARRAY);
  3276. GLSL_TYPE(GL_INT_IMAGE_2D);
  3277. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D);
  3278. GLSL_TYPE(GL_IMAGE_3D);
  3279. GLSL_TYPE(GL_INT_IMAGE_3D);
  3280. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D);
  3281. GLSL_TYPE(GL_IMAGE_CUBE);
  3282. GLSL_TYPE(GL_INT_IMAGE_CUBE);
  3283. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE);
  3284. }
  3285. #undef GLSL_TYPE
  3286. BX_CHECK(false, "Unknown GLSL type? %x", _type);
  3287. return "UNKNOWN GLSL TYPE!";
  3288. }
  3289. const char* glEnumName(GLenum _enum)
  3290. {
  3291. #define GLENUM(_ty) case _ty: return #_ty
  3292. switch (_enum)
  3293. {
  3294. GLENUM(GL_TEXTURE);
  3295. GLENUM(GL_RENDERBUFFER);
  3296. GLENUM(GL_INVALID_ENUM);
  3297. GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION);
  3298. GLENUM(GL_INVALID_VALUE);
  3299. GLENUM(GL_INVALID_OPERATION);
  3300. GLENUM(GL_OUT_OF_MEMORY);
  3301. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
  3302. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
  3303. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
  3304. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
  3305. GLENUM(GL_FRAMEBUFFER_UNSUPPORTED);
  3306. }
  3307. #undef GLENUM
  3308. BX_WARN(false, "Unknown enum? %x", _enum);
  3309. return "<GLenum?>";
  3310. }
  3311. UniformType::Enum convertGlType(GLenum _type)
  3312. {
  3313. switch (_type)
  3314. {
  3315. case GL_INT:
  3316. case GL_UNSIGNED_INT:
  3317. return UniformType::Int1;
  3318. case GL_FLOAT:
  3319. case GL_FLOAT_VEC2:
  3320. case GL_FLOAT_VEC3:
  3321. case GL_FLOAT_VEC4:
  3322. return UniformType::Vec4;
  3323. case GL_FLOAT_MAT2:
  3324. break;
  3325. case GL_FLOAT_MAT3:
  3326. return UniformType::Mat3;
  3327. case GL_FLOAT_MAT4:
  3328. return UniformType::Mat4;
  3329. case GL_SAMPLER_2D:
  3330. case GL_SAMPLER_2D_ARRAY:
  3331. case GL_SAMPLER_2D_MULTISAMPLE:
  3332. case GL_INT_SAMPLER_2D:
  3333. case GL_INT_SAMPLER_2D_ARRAY:
  3334. case GL_INT_SAMPLER_2D_MULTISAMPLE:
  3335. case GL_UNSIGNED_INT_SAMPLER_2D:
  3336. case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
  3337. case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
  3338. case GL_SAMPLER_2D_SHADOW:
  3339. case GL_SAMPLER_2D_ARRAY_SHADOW:
  3340. case GL_SAMPLER_3D:
  3341. case GL_INT_SAMPLER_3D:
  3342. case GL_UNSIGNED_INT_SAMPLER_3D:
  3343. case GL_SAMPLER_CUBE:
  3344. case GL_INT_SAMPLER_CUBE:
  3345. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3346. case GL_IMAGE_1D:
  3347. case GL_INT_IMAGE_1D:
  3348. case GL_UNSIGNED_INT_IMAGE_1D:
  3349. case GL_IMAGE_2D:
  3350. case GL_IMAGE_2D_ARRAY:
  3351. case GL_INT_IMAGE_2D:
  3352. case GL_UNSIGNED_INT_IMAGE_2D:
  3353. case GL_IMAGE_3D:
  3354. case GL_INT_IMAGE_3D:
  3355. case GL_UNSIGNED_INT_IMAGE_3D:
  3356. case GL_IMAGE_CUBE:
  3357. case GL_INT_IMAGE_CUBE:
  3358. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3359. return UniformType::Int1;
  3360. };
  3361. BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type);
  3362. return UniformType::End;
  3363. }
  3364. void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh)
  3365. {
  3366. m_id = glCreateProgram();
  3367. BX_TRACE("Program create: GL%d: GL%d, GL%d", m_id, _vsh.m_id, _fsh.m_id);
  3368. const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  3369. const bool cached = s_renderGL->programFetchFromCache(m_id, id);
  3370. if (!cached)
  3371. {
  3372. GLint linked = 0;
  3373. if (0 != _vsh.m_id)
  3374. {
  3375. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  3376. if (0 != _fsh.m_id)
  3377. {
  3378. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  3379. }
  3380. GL_CHECK(glLinkProgram(m_id) );
  3381. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  3382. if (0 == linked)
  3383. {
  3384. char log[1024];
  3385. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  3386. BX_TRACE("%d: %s", linked, log);
  3387. }
  3388. }
  3389. if (0 == linked)
  3390. {
  3391. BX_WARN(0 != _vsh.m_id, "Invalid vertex/compute shader.");
  3392. GL_CHECK(glDeleteProgram(m_id) );
  3393. m_used[0] = Attrib::Count;
  3394. m_id = 0;
  3395. return;
  3396. }
  3397. s_renderGL->programCache(m_id, id);
  3398. }
  3399. init();
  3400. if (!cached)
  3401. {
  3402. // Must be after init, otherwise init might fail to lookup shader
  3403. // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003).
  3404. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  3405. if (0 != _fsh.m_id)
  3406. {
  3407. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  3408. }
  3409. }
  3410. }
  3411. void ProgramGL::destroy()
  3412. {
  3413. if (NULL != m_constantBuffer)
  3414. {
  3415. UniformBuffer::destroy(m_constantBuffer);
  3416. m_constantBuffer = NULL;
  3417. }
  3418. m_numPredefined = 0;
  3419. if (0 != m_id)
  3420. {
  3421. GL_CHECK(glUseProgram(0) );
  3422. GL_CHECK(glDeleteProgram(m_id) );
  3423. m_id = 0;
  3424. }
  3425. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3426. }
  3427. void ProgramGL::init()
  3428. {
  3429. GLint activeAttribs = 0;
  3430. GLint activeUniforms = 0;
  3431. GLint activeBuffers = 0;
  3432. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  3433. GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") );
  3434. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  3435. GLint max0, max1;
  3436. bool piqSupported = true
  3437. && s_extension[Extension::ARB_program_interface_query ].m_supported
  3438. && s_extension[Extension::ARB_shader_storage_buffer_object].m_supported
  3439. ;
  3440. if (piqSupported)
  3441. {
  3442. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) );
  3443. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) );
  3444. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) );
  3445. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_MAX_NAME_LENGTH, &max0 ) );
  3446. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_MAX_NAME_LENGTH, &max1 ) );
  3447. }
  3448. else
  3449. {
  3450. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) );
  3451. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  3452. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  3453. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  3454. }
  3455. uint32_t maxLength = bx::uint32_max(max0, max1);
  3456. char* name = (char*)alloca(maxLength + 1);
  3457. BX_TRACE("Program %d", m_id);
  3458. BX_TRACE("Attributes (%d):", activeAttribs);
  3459. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  3460. {
  3461. GLint size;
  3462. GLenum type = 0;
  3463. if (piqSupported)
  3464. {
  3465. GL_CHECK(glGetProgramResourceName(m_id, GL_PROGRAM_INPUT, ii, maxLength + 1, &size, name) );
  3466. GLenum typeProp[] = { GL_TYPE };
  3467. GL_CHECK(glGetProgramResourceiv(m_id
  3468. , GL_PROGRAM_INPUT
  3469. , ii
  3470. , BX_COUNTOF(typeProp)
  3471. , typeProp
  3472. , 1
  3473. , NULL
  3474. , (GLint *)&type)
  3475. );
  3476. }
  3477. else
  3478. {
  3479. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  3480. }
  3481. BX_TRACE("\t%s %s is at location %d"
  3482. , glslTypeName(type)
  3483. , name
  3484. , glGetAttribLocation(m_id, name)
  3485. );
  3486. }
  3487. m_numPredefined = 0;
  3488. m_numSamplers = 0;
  3489. BX_TRACE("Uniforms (%d):", activeUniforms);
  3490. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  3491. {
  3492. struct VariableInfo
  3493. {
  3494. GLenum type;
  3495. GLint loc;
  3496. GLint num;
  3497. };
  3498. VariableInfo vi;
  3499. GLenum props[] ={ GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE };
  3500. GLenum gltype;
  3501. GLint num;
  3502. GLint loc;
  3503. if (piqSupported)
  3504. {
  3505. GL_CHECK(glGetProgramResourceiv(m_id
  3506. , GL_UNIFORM
  3507. , ii
  3508. , BX_COUNTOF(props)
  3509. , props
  3510. , BX_COUNTOF(props)
  3511. , NULL
  3512. , (GLint*)&vi
  3513. ) );
  3514. GL_CHECK(glGetProgramResourceName(m_id
  3515. , GL_UNIFORM
  3516. , ii
  3517. , maxLength + 1
  3518. , NULL
  3519. , name
  3520. ) );
  3521. gltype = vi.type;
  3522. loc = vi.loc;
  3523. num = vi.num;
  3524. }
  3525. else
  3526. {
  3527. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  3528. loc = glGetUniformLocation(m_id, name);
  3529. }
  3530. num = bx::uint32_max(num, 1);
  3531. int offset = 0;
  3532. char* array = strchr(name, '[');
  3533. if (NULL != array)
  3534. {
  3535. BX_TRACE("--- %s", name);
  3536. *array = '\0';
  3537. array++;
  3538. char* end = strchr(array, ']');
  3539. if (NULL != end)
  3540. { // Some devices (Amazon Fire) might not return terminating brace.
  3541. *end = '\0';
  3542. offset = atoi(array);
  3543. }
  3544. }
  3545. switch (gltype)
  3546. {
  3547. case GL_SAMPLER_2D:
  3548. case GL_SAMPLER_2D_ARRAY:
  3549. case GL_SAMPLER_2D_MULTISAMPLE:
  3550. case GL_INT_SAMPLER_2D:
  3551. case GL_INT_SAMPLER_2D_ARRAY:
  3552. case GL_INT_SAMPLER_2D_MULTISAMPLE:
  3553. case GL_UNSIGNED_INT_SAMPLER_2D:
  3554. case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
  3555. case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
  3556. case GL_SAMPLER_2D_SHADOW:
  3557. case GL_SAMPLER_2D_ARRAY_SHADOW:
  3558. case GL_SAMPLER_3D:
  3559. case GL_INT_SAMPLER_3D:
  3560. case GL_UNSIGNED_INT_SAMPLER_3D:
  3561. case GL_SAMPLER_CUBE:
  3562. case GL_INT_SAMPLER_CUBE:
  3563. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  3564. case GL_IMAGE_1D:
  3565. case GL_INT_IMAGE_1D:
  3566. case GL_UNSIGNED_INT_IMAGE_1D:
  3567. case GL_IMAGE_2D:
  3568. case GL_INT_IMAGE_2D:
  3569. case GL_UNSIGNED_INT_IMAGE_2D:
  3570. case GL_IMAGE_3D:
  3571. case GL_INT_IMAGE_3D:
  3572. case GL_UNSIGNED_INT_IMAGE_3D:
  3573. case GL_IMAGE_CUBE:
  3574. case GL_INT_IMAGE_CUBE:
  3575. case GL_UNSIGNED_INT_IMAGE_CUBE:
  3576. if (m_numSamplers < BX_COUNTOF(m_sampler) )
  3577. {
  3578. BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc);
  3579. m_sampler[m_numSamplers] = loc;
  3580. m_numSamplers++;
  3581. }
  3582. else
  3583. {
  3584. BX_TRACE("Too many samplers (max: %d)! Sampler at location %d."
  3585. , BX_COUNTOF(m_sampler)
  3586. , loc
  3587. );
  3588. }
  3589. break;
  3590. default:
  3591. break;
  3592. }
  3593. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  3594. if (PredefinedUniform::Count != predefined)
  3595. {
  3596. m_predefined[m_numPredefined].m_loc = loc;
  3597. m_predefined[m_numPredefined].m_count = uint16_t(num);
  3598. m_predefined[m_numPredefined].m_type = uint8_t(predefined);
  3599. m_numPredefined++;
  3600. }
  3601. else
  3602. {
  3603. const UniformInfo* info = s_renderGL->m_uniformReg.find(name);
  3604. BX_WARN(NULL != info, "User defined uniform '%s' is not found, it won't be set.", name);
  3605. if (NULL != info)
  3606. {
  3607. if (NULL == m_constantBuffer)
  3608. {
  3609. m_constantBuffer = UniformBuffer::create(1024);
  3610. }
  3611. UniformType::Enum type = convertGlType(gltype);
  3612. m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, uint16_t(num) );
  3613. m_constantBuffer->write(loc);
  3614. BX_TRACE("store %s %d", name, info->m_handle);
  3615. }
  3616. }
  3617. BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d"
  3618. , glslTypeName(gltype)
  3619. , name
  3620. , PredefinedUniform::Count != predefined ? "*" : ""
  3621. , loc
  3622. , num
  3623. , offset
  3624. );
  3625. BX_UNUSED(offset);
  3626. }
  3627. if (NULL != m_constantBuffer)
  3628. {
  3629. m_constantBuffer->finish();
  3630. }
  3631. if (piqSupported)
  3632. {
  3633. struct VariableInfo
  3634. {
  3635. GLenum type;
  3636. };
  3637. VariableInfo vi;
  3638. GLenum props[] = { GL_TYPE };
  3639. BX_TRACE("Buffers (%d):", activeBuffers);
  3640. for (int32_t ii = 0; ii < activeBuffers; ++ii)
  3641. {
  3642. GL_CHECK(glGetProgramResourceiv(m_id
  3643. , GL_BUFFER_VARIABLE
  3644. , ii
  3645. , BX_COUNTOF(props)
  3646. , props
  3647. , BX_COUNTOF(props)
  3648. , NULL
  3649. , (GLint*)&vi
  3650. ) );
  3651. GL_CHECK(glGetProgramResourceName(m_id
  3652. , GL_BUFFER_VARIABLE
  3653. , ii
  3654. , maxLength + 1
  3655. , NULL
  3656. , name
  3657. ) );
  3658. BX_TRACE("\t%s %s at %d"
  3659. , glslTypeName(vi.type)
  3660. , name
  3661. , 0 //vi.loc
  3662. );
  3663. }
  3664. }
  3665. memset(m_attributes, 0xff, sizeof(m_attributes) );
  3666. uint32_t used = 0;
  3667. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  3668. {
  3669. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  3670. if (-1 != loc)
  3671. {
  3672. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  3673. m_attributes[ii] = loc;
  3674. m_used[used++] = ii;
  3675. }
  3676. }
  3677. BX_CHECK(used < BX_COUNTOF(m_used), "Out of bounds %d > array size %d."
  3678. , used
  3679. , BX_COUNTOF(m_used)
  3680. );
  3681. m_used[used] = Attrib::Count;
  3682. used = 0;
  3683. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  3684. {
  3685. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  3686. if (GLuint(-1) != loc )
  3687. {
  3688. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  3689. m_instanceData[used++] = loc;
  3690. }
  3691. }
  3692. BX_CHECK(used < BX_COUNTOF(m_instanceData), "Out of bounds %d > array size %d."
  3693. , used
  3694. , BX_COUNTOF(m_instanceData)
  3695. );
  3696. m_instanceData[used] = 0xffff;
  3697. }
  3698. void ProgramGL::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex) const
  3699. {
  3700. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  3701. {
  3702. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  3703. GLint loc = m_attributes[attr];
  3704. uint8_t num;
  3705. AttribType::Enum type;
  3706. bool normalized;
  3707. bool asInt;
  3708. _vertexDecl.decode(attr, num, type, normalized, asInt);
  3709. if (-1 != loc)
  3710. {
  3711. if (UINT16_MAX != _vertexDecl.m_attributes[attr])
  3712. {
  3713. GL_CHECK(glEnableVertexAttribArray(loc) );
  3714. GL_CHECK(glVertexAttribDivisor(loc, 0) );
  3715. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  3716. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 30) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  3717. && (AttribType::Uint8 == type || AttribType::Int16 == type)
  3718. && !normalized)
  3719. {
  3720. GL_CHECK(glVertexAttribIPointer(loc
  3721. , num
  3722. , s_attribType[type]
  3723. , _vertexDecl.m_stride
  3724. , (void*)(uintptr_t)baseVertex)
  3725. );
  3726. }
  3727. else
  3728. {
  3729. GL_CHECK(glVertexAttribPointer(loc
  3730. , num
  3731. , s_attribType[type]
  3732. , normalized
  3733. , _vertexDecl.m_stride
  3734. , (void*)(uintptr_t)baseVertex)
  3735. );
  3736. }
  3737. }
  3738. else
  3739. {
  3740. GL_CHECK(glDisableVertexAttribArray(loc) );
  3741. }
  3742. }
  3743. }
  3744. }
  3745. void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  3746. {
  3747. uint32_t baseVertex = _baseVertex;
  3748. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  3749. {
  3750. GLint loc = m_instanceData[ii];
  3751. GL_CHECK(glEnableVertexAttribArray(loc) );
  3752. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  3753. GL_CHECK(glVertexAttribDivisor(loc, 1) );
  3754. baseVertex += 16;
  3755. }
  3756. }
  3757. void IndexBufferGL::destroy()
  3758. {
  3759. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  3760. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3761. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3762. }
  3763. void VertexBufferGL::destroy()
  3764. {
  3765. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  3766. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3767. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3768. }
  3769. static void texSubImage(
  3770. GLenum _target
  3771. , GLint _level
  3772. , GLint _xoffset
  3773. , GLint _yoffset
  3774. , GLint _zoffset
  3775. , GLsizei _width
  3776. , GLsizei _height
  3777. , GLsizei _depth
  3778. , GLenum _format
  3779. , GLenum _type
  3780. , const GLvoid* _data
  3781. )
  3782. {
  3783. if (NULL == _data)
  3784. {
  3785. return;
  3786. }
  3787. if (_target == GL_TEXTURE_3D
  3788. || _target == GL_TEXTURE_2D_ARRAY
  3789. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  3790. {
  3791. GL_CHECK(glTexSubImage3D(
  3792. _target
  3793. , _level
  3794. , _xoffset
  3795. , _yoffset
  3796. , _zoffset
  3797. , _width
  3798. , _height
  3799. , _depth
  3800. , _format
  3801. , _type
  3802. , _data
  3803. ) );
  3804. }
  3805. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  3806. {
  3807. }
  3808. else
  3809. {
  3810. BX_UNUSED(_zoffset, _depth);
  3811. GL_CHECK(glTexSubImage2D(
  3812. _target
  3813. , _level
  3814. , _xoffset
  3815. , _yoffset
  3816. , _width
  3817. , _height
  3818. , _format
  3819. , _type
  3820. , _data
  3821. ) );
  3822. }
  3823. }
  3824. static void texImage(
  3825. GLenum _target
  3826. , uint32_t _msaaQuality
  3827. , GLint _level
  3828. , GLint _internalFormat
  3829. , GLsizei _width
  3830. , GLsizei _height
  3831. , GLsizei _depth
  3832. , GLint _border
  3833. , GLenum _format
  3834. , GLenum _type
  3835. , const GLvoid* _data
  3836. )
  3837. {
  3838. if (_target == GL_TEXTURE_3D)
  3839. {
  3840. GL_CHECK(glTexImage3D(
  3841. _target
  3842. , _level
  3843. , _internalFormat
  3844. , _width
  3845. , _height
  3846. , _depth
  3847. , _border
  3848. , _format
  3849. , _type
  3850. , _data
  3851. ) );
  3852. }
  3853. else if (_target == GL_TEXTURE_2D_ARRAY
  3854. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  3855. {
  3856. texSubImage(
  3857. _target
  3858. , _level
  3859. , 0
  3860. , 0
  3861. , _depth
  3862. , _width
  3863. , _height
  3864. , 1
  3865. , _format
  3866. , _type
  3867. , _data
  3868. );
  3869. }
  3870. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  3871. {
  3872. }
  3873. else if (_target == GL_TEXTURE_2D_MULTISAMPLE)
  3874. {
  3875. GL_CHECK(glTexImage2DMultisample(
  3876. _target
  3877. , _msaaQuality
  3878. , _internalFormat
  3879. , _width
  3880. , _height
  3881. , false
  3882. ) );
  3883. }
  3884. else
  3885. {
  3886. GL_CHECK(glTexImage2D(
  3887. _target
  3888. , _level
  3889. , _internalFormat
  3890. , _width
  3891. , _height
  3892. , _border
  3893. , _format
  3894. , _type
  3895. , _data
  3896. ) );
  3897. }
  3898. BX_UNUSED(_msaaQuality, _depth, _border, _data);
  3899. }
  3900. static void compressedTexSubImage(
  3901. GLenum _target
  3902. , GLint _level
  3903. , GLint _xoffset
  3904. , GLint _yoffset
  3905. , GLint _zoffset
  3906. , GLsizei _width
  3907. , GLsizei _height
  3908. , GLsizei _depth
  3909. , GLenum _format
  3910. , GLsizei _imageSize
  3911. , const GLvoid* _data
  3912. )
  3913. {
  3914. if (_target == GL_TEXTURE_3D)
  3915. {
  3916. GL_CHECK(glCompressedTexSubImage3D(
  3917. _target
  3918. , _level
  3919. , _xoffset
  3920. , _yoffset
  3921. , _zoffset
  3922. , _width
  3923. , _height
  3924. , _depth
  3925. , _format
  3926. , _imageSize
  3927. , _data
  3928. ) );
  3929. }
  3930. else
  3931. {
  3932. BX_UNUSED(_zoffset, _depth);
  3933. GL_CHECK(glCompressedTexSubImage2D(
  3934. _target
  3935. , _level
  3936. , _xoffset
  3937. , _yoffset
  3938. , _width
  3939. , _height
  3940. , _format
  3941. , _imageSize
  3942. , _data
  3943. ) );
  3944. }
  3945. }
  3946. static void compressedTexImage(
  3947. GLenum _target
  3948. , GLint _level
  3949. , GLenum _internalformat
  3950. , GLsizei _width
  3951. , GLsizei _height
  3952. , GLsizei _depth
  3953. , GLint _border
  3954. , GLsizei _imageSize
  3955. , const GLvoid* _data
  3956. )
  3957. {
  3958. if (_target == GL_TEXTURE_3D)
  3959. {
  3960. GL_CHECK(glCompressedTexImage3D(
  3961. _target
  3962. , _level
  3963. , _internalformat
  3964. , _width
  3965. , _height
  3966. , _depth
  3967. , _border
  3968. , _imageSize
  3969. , _data
  3970. ) );
  3971. }
  3972. else if (_target == GL_TEXTURE_2D_ARRAY
  3973. || _target == GL_TEXTURE_CUBE_MAP_ARRAY)
  3974. {
  3975. compressedTexSubImage(_target, _level, 0, 0, _depth, _width, _height, 1, _internalformat, _imageSize, _data);
  3976. }
  3977. else if (_target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)
  3978. {
  3979. }
  3980. else
  3981. {
  3982. BX_UNUSED(_depth);
  3983. GL_CHECK(glCompressedTexImage2D(
  3984. _target
  3985. , _level
  3986. , _internalformat
  3987. , _width
  3988. , _height
  3989. , _border
  3990. , _imageSize
  3991. , _data
  3992. ) );
  3993. }
  3994. }
  3995. bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _numMips, uint32_t _flags)
  3996. {
  3997. m_target = _target;
  3998. m_numMips = _numMips;
  3999. m_flags = _flags;
  4000. m_width = _width;
  4001. m_height = _height;
  4002. m_depth = _depth;
  4003. m_currentSamplerHash = UINT32_MAX;
  4004. const bool writeOnly = 0 != (m_flags&BGFX_TEXTURE_RT_WRITE_ONLY);
  4005. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE );
  4006. const bool textureArray = false
  4007. || _target == GL_TEXTURE_2D_ARRAY
  4008. || _target == GL_TEXTURE_CUBE_MAP_ARRAY
  4009. ;
  4010. if (!writeOnly)
  4011. {
  4012. GL_CHECK(glGenTextures(1, &m_id) );
  4013. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  4014. GL_CHECK(glBindTexture(_target, m_id) );
  4015. const TextureFormatInfo& tfi = s_textureFormat[m_textureFormat];
  4016. m_fmt = tfi.m_fmt;
  4017. m_type = tfi.m_type;
  4018. const bool swizzle = true
  4019. && TextureFormat::BGRA8 == m_requestedFormat
  4020. && !s_textureFormat[m_requestedFormat].m_supported
  4021. && !s_renderGL->m_textureSwizzleSupport
  4022. ;
  4023. const bool convert = false
  4024. || m_textureFormat != m_requestedFormat
  4025. || swizzle
  4026. ;
  4027. if (convert)
  4028. {
  4029. m_textureFormat = (uint8_t)TextureFormat::RGBA8;
  4030. const TextureFormatInfo& tfiRgba8 = s_textureFormat[TextureFormat::RGBA8];
  4031. m_fmt = tfiRgba8.m_fmt;
  4032. m_type = tfiRgba8.m_type;
  4033. }
  4034. if (textureArray)
  4035. {
  4036. GL_CHECK(glTexStorage3D(_target
  4037. , _numMips
  4038. , s_textureFormat[m_textureFormat].m_internalFmt
  4039. , m_width
  4040. , m_height
  4041. , _depth
  4042. ) );
  4043. }
  4044. if (computeWrite)
  4045. {
  4046. if (_target == GL_TEXTURE_3D)
  4047. {
  4048. GL_CHECK(glTexStorage3D(_target
  4049. , _numMips
  4050. , s_textureFormat[m_textureFormat].m_internalFmt
  4051. , m_width
  4052. , m_height
  4053. , _depth
  4054. ) );
  4055. }
  4056. else
  4057. {
  4058. GL_CHECK(glTexStorage2D(_target
  4059. , _numMips
  4060. , s_textureFormat[m_textureFormat].m_internalFmt
  4061. , m_width
  4062. , m_height
  4063. ) );
  4064. }
  4065. }
  4066. setSamplerState(_flags, NULL);
  4067. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4068. && TextureFormat::BGRA8 == m_requestedFormat
  4069. && !s_textureFormat[m_requestedFormat].m_supported
  4070. && s_renderGL->m_textureSwizzleSupport)
  4071. {
  4072. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  4073. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  4074. }
  4075. }
  4076. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  4077. if (renderTarget)
  4078. {
  4079. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  4080. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  4081. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  4082. const bool msaaSample = 0 != (m_flags&BGFX_TEXTURE_MSAA_SAMPLE);
  4083. if (!msaaSample
  4084. && (0 != msaaQuality || writeOnly) )
  4085. {
  4086. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  4087. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  4088. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  4089. if (0 == msaaQuality)
  4090. {
  4091. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER
  4092. , s_rboFormat[m_textureFormat]
  4093. , _width
  4094. , _height
  4095. ) );
  4096. }
  4097. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4098. {
  4099. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER
  4100. , msaaQuality
  4101. , s_rboFormat[m_textureFormat]
  4102. , _width
  4103. , _height
  4104. ) );
  4105. }
  4106. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  4107. if (writeOnly)
  4108. {
  4109. // This is render buffer, there is no sampling, no need
  4110. // to create texture.
  4111. return false;
  4112. }
  4113. }
  4114. }
  4115. return true;
  4116. }
  4117. void TextureGL::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  4118. {
  4119. ImageContainer imageContainer;
  4120. if (imageParse(imageContainer, _mem->data, _mem->size) )
  4121. {
  4122. uint8_t numMips = imageContainer.m_numMips;
  4123. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  4124. numMips -= startLod;
  4125. const uint16_t numLayers = imageContainer.m_numLayers;
  4126. uint32_t textureWidth;
  4127. uint32_t textureHeight;
  4128. uint32_t textureDepth;
  4129. {
  4130. const ImageBlockInfo& ibi = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  4131. textureWidth = bx::uint32_max(ibi.blockWidth, imageContainer.m_width >>startLod);
  4132. textureHeight = bx::uint32_max(ibi.blockHeight, imageContainer.m_height>>startLod);
  4133. textureDepth = 1 < imageContainer.m_depth
  4134. ? imageContainer.m_depth
  4135. : imageContainer.m_numLayers
  4136. ;
  4137. }
  4138. m_requestedFormat = uint8_t(imageContainer.m_format);
  4139. m_textureFormat = uint8_t(getViableTextureFormat(imageContainer) );
  4140. const bool computeWrite = 0 != (_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  4141. const bool srgb = 0 != (_flags&BGFX_TEXTURE_SRGB);
  4142. const bool msaaSample = 0 != (_flags&BGFX_TEXTURE_MSAA_SAMPLE);
  4143. uint32_t msaaQuality = ( (_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  4144. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  4145. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  4146. GLenum target = msaaSample ? GL_TEXTURE_2D_MULTISAMPLE : GL_TEXTURE_2D;
  4147. if (imageContainer.m_cubeMap)
  4148. {
  4149. target = GL_TEXTURE_CUBE_MAP;
  4150. }
  4151. else if (imageContainer.m_depth > 1)
  4152. {
  4153. target = GL_TEXTURE_3D;
  4154. }
  4155. const bool textureArray = 1 < numLayers;
  4156. if (textureArray)
  4157. {
  4158. switch (target)
  4159. {
  4160. case GL_TEXTURE_CUBE_MAP: target = GL_TEXTURE_CUBE_MAP_ARRAY;
  4161. case GL_TEXTURE_2D_MULTISAMPLE: target = GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
  4162. default: target = GL_TEXTURE_2D_ARRAY;
  4163. }
  4164. }
  4165. if (!init(target
  4166. , textureWidth
  4167. , textureHeight
  4168. , textureDepth
  4169. , numMips
  4170. , _flags
  4171. ) )
  4172. {
  4173. return;
  4174. }
  4175. target = isCubeMap()
  4176. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X
  4177. : m_target
  4178. ;
  4179. const GLenum internalFmt = srgb
  4180. ? s_textureFormat[m_textureFormat].m_internalFmtSrgb
  4181. : s_textureFormat[m_textureFormat].m_internalFmt
  4182. ;
  4183. const bool swizzle = true
  4184. && TextureFormat::BGRA8 == m_requestedFormat
  4185. && !s_textureFormat[m_requestedFormat].m_supported
  4186. && !s_renderGL->m_textureSwizzleSupport
  4187. ;
  4188. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  4189. const bool convert = false
  4190. || m_textureFormat != m_requestedFormat
  4191. || swizzle
  4192. ;
  4193. BX_TRACE("Texture%-4s %3d: %s (requested: %s), layers %d, %dx%dx%d%s."
  4194. , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D")
  4195. , this - s_renderGL->m_textures
  4196. , getName( (TextureFormat::Enum)m_textureFormat)
  4197. , getName( (TextureFormat::Enum)m_requestedFormat)
  4198. , numLayers
  4199. , textureWidth
  4200. , textureHeight
  4201. , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0)
  4202. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  4203. );
  4204. BX_WARN(!convert, "Texture %s%s%s from %s to %s."
  4205. , swizzle ? "swizzle" : ""
  4206. , swizzle&&convert ? " and " : ""
  4207. , convert ? "convert" : ""
  4208. , getName( (TextureFormat::Enum)m_requestedFormat)
  4209. , getName( (TextureFormat::Enum)m_textureFormat)
  4210. );
  4211. uint8_t* temp = NULL;
  4212. if (convert)
  4213. {
  4214. temp = (uint8_t*)BX_ALLOC(g_allocator, textureWidth*textureHeight*4);
  4215. }
  4216. const uint16_t numSides = numLayers * (imageContainer.m_cubeMap ? 6 : 1);
  4217. for (uint16_t side = 0; side < numSides; ++side)
  4218. {
  4219. uint32_t width = textureWidth;
  4220. uint32_t height = textureHeight;
  4221. uint32_t depth = imageContainer.m_depth;
  4222. GLenum imageTarget = imageContainer.m_cubeMap && !textureArray
  4223. ? target+side
  4224. : target
  4225. ;
  4226. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  4227. {
  4228. width = bx::uint32_max(1, width);
  4229. height = bx::uint32_max(1, height);
  4230. depth = 1 < imageContainer.m_depth
  4231. ? bx::uint32_max(1, depth)
  4232. : side
  4233. ;
  4234. ImageMip mip;
  4235. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  4236. {
  4237. if (compressed
  4238. && !convert)
  4239. {
  4240. compressedTexImage(imageTarget
  4241. , lod
  4242. , internalFmt
  4243. , width
  4244. , height
  4245. , depth
  4246. , 0
  4247. , mip.m_size
  4248. , mip.m_data
  4249. );
  4250. }
  4251. else
  4252. {
  4253. const uint8_t* data = mip.m_data;
  4254. if (convert)
  4255. {
  4256. imageDecodeToRgba8(temp
  4257. , mip.m_data
  4258. , mip.m_width
  4259. , mip.m_height
  4260. , mip.m_width*4
  4261. , mip.m_format
  4262. );
  4263. data = temp;
  4264. }
  4265. texImage(imageTarget
  4266. , msaaQuality
  4267. , lod
  4268. , internalFmt
  4269. , width
  4270. , height
  4271. , depth
  4272. , 0
  4273. , m_fmt
  4274. , m_type
  4275. , data
  4276. );
  4277. }
  4278. }
  4279. else if (!computeWrite)
  4280. {
  4281. if (compressed)
  4282. {
  4283. uint32_t size = bx::uint32_max(1, (width + 3)>>2)
  4284. * bx::uint32_max(1, (height + 3)>>2)
  4285. * 4*4*getBitsPerPixel(TextureFormat::Enum(m_textureFormat) )/8
  4286. ;
  4287. compressedTexImage(imageTarget
  4288. , lod
  4289. , internalFmt
  4290. , width
  4291. , height
  4292. , depth
  4293. , 0
  4294. , size
  4295. , NULL
  4296. );
  4297. }
  4298. else
  4299. {
  4300. texImage(imageTarget
  4301. , msaaQuality
  4302. , lod
  4303. , internalFmt
  4304. , width
  4305. , height
  4306. , depth
  4307. , 0
  4308. , m_fmt
  4309. , m_type
  4310. , NULL
  4311. );
  4312. }
  4313. }
  4314. width >>= 1;
  4315. height >>= 1;
  4316. depth >>= 1;
  4317. }
  4318. }
  4319. if (NULL != temp)
  4320. {
  4321. BX_FREE(g_allocator, temp);
  4322. }
  4323. }
  4324. GL_CHECK(glBindTexture(m_target, 0) );
  4325. }
  4326. void TextureGL::destroy()
  4327. {
  4328. if (0 == (m_flags & BGFX_TEXTURE_INTERNAL_SHARED)
  4329. && 0 != m_id)
  4330. {
  4331. GL_CHECK(glBindTexture(m_target, 0) );
  4332. GL_CHECK(glDeleteTextures(1, &m_id) );
  4333. m_id = 0;
  4334. }
  4335. if (0 != m_rbo)
  4336. {
  4337. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  4338. m_rbo = 0;
  4339. }
  4340. }
  4341. void TextureGL::overrideInternal(uintptr_t _ptr)
  4342. {
  4343. destroy();
  4344. m_flags |= BGFX_TEXTURE_INTERNAL_SHARED;
  4345. m_id = (GLuint)_ptr;
  4346. }
  4347. void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  4348. {
  4349. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  4350. const uint32_t rectpitch = _rect.m_width*bpp/8;
  4351. uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  4352. GL_CHECK(glBindTexture(m_target, m_id) );
  4353. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  4354. GLenum target = isCubeMap()
  4355. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X
  4356. : m_target
  4357. ;
  4358. const bool swizzle = true
  4359. && TextureFormat::BGRA8 == m_requestedFormat
  4360. && !s_textureFormat[m_requestedFormat].m_supported
  4361. && !s_renderGL->m_textureSwizzleSupport
  4362. ;
  4363. const bool unpackRowLength = BX_IGNORE_C4127(!!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported);
  4364. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  4365. const bool convert = false
  4366. || (compressed && m_textureFormat != m_requestedFormat)
  4367. || swizzle
  4368. ;
  4369. const uint32_t width = _rect.m_width;
  4370. const uint32_t height = _rect.m_height;
  4371. uint8_t* temp = NULL;
  4372. if (convert
  4373. || !unpackRowLength)
  4374. {
  4375. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height);
  4376. }
  4377. else if (unpackRowLength)
  4378. {
  4379. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) );
  4380. }
  4381. if (compressed)
  4382. {
  4383. const uint8_t* data = _mem->data;
  4384. if (!unpackRowLength)
  4385. {
  4386. imageCopy(width, height, bpp, srcpitch, data, temp);
  4387. data = temp;
  4388. }
  4389. GL_CHECK(compressedTexSubImage(target+_side
  4390. , _mip
  4391. , _rect.m_x
  4392. , _rect.m_y
  4393. , _z
  4394. , _rect.m_width
  4395. , _rect.m_height
  4396. , _depth
  4397. , m_fmt
  4398. , _mem->size
  4399. , data
  4400. ) );
  4401. }
  4402. else
  4403. {
  4404. const uint8_t* data = _mem->data;
  4405. if (convert)
  4406. {
  4407. imageDecodeToRgba8(temp, data, width, height, srcpitch, TextureFormat::Enum(m_requestedFormat) );
  4408. data = temp;
  4409. srcpitch = rectpitch;
  4410. }
  4411. if (!unpackRowLength
  4412. && !convert)
  4413. {
  4414. imageCopy(width, height, bpp, srcpitch, data, temp);
  4415. data = temp;
  4416. }
  4417. GL_CHECK(texSubImage(target+_side
  4418. , _mip
  4419. , _rect.m_x
  4420. , _rect.m_y
  4421. , _z
  4422. , _rect.m_width
  4423. , _rect.m_height
  4424. , _depth
  4425. , m_fmt
  4426. , m_type
  4427. , data
  4428. ) );
  4429. }
  4430. if (!convert
  4431. && unpackRowLength)
  4432. {
  4433. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) );
  4434. }
  4435. if (NULL != temp)
  4436. {
  4437. BX_FREE(g_allocator, temp);
  4438. }
  4439. }
  4440. void TextureGL::setSamplerState(uint32_t _flags, const float _rgba[4])
  4441. {
  4442. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  4443. && !s_textureFilter[m_textureFormat])
  4444. {
  4445. // Force point sampling when texture format doesn't support linear sampling.
  4446. _flags &= ~(0
  4447. | BGFX_TEXTURE_MIN_MASK
  4448. | BGFX_TEXTURE_MAG_MASK
  4449. | BGFX_TEXTURE_MIP_MASK
  4450. );
  4451. _flags |= 0
  4452. | BGFX_TEXTURE_MIN_POINT
  4453. | BGFX_TEXTURE_MAG_POINT
  4454. | BGFX_TEXTURE_MIP_POINT
  4455. ;
  4456. }
  4457. const uint32_t flags = (0 != (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags) ? m_flags : _flags) & BGFX_TEXTURE_SAMPLER_BITS_MASK;
  4458. bool hasBorderColor = false;
  4459. bx::HashMurmur2A murmur;
  4460. murmur.begin();
  4461. murmur.add(flags);
  4462. if (NULL != _rgba)
  4463. {
  4464. if (BGFX_TEXTURE_U_BORDER == (flags & BGFX_TEXTURE_U_BORDER)
  4465. || BGFX_TEXTURE_V_BORDER == (flags & BGFX_TEXTURE_V_BORDER)
  4466. || BGFX_TEXTURE_W_BORDER == (flags & BGFX_TEXTURE_W_BORDER) )
  4467. {
  4468. murmur.add(_rgba, 16);
  4469. hasBorderColor = true;
  4470. }
  4471. }
  4472. uint32_t hash = murmur.end();
  4473. if (hash != m_currentSamplerHash)
  4474. {
  4475. const GLenum target = m_target == GL_TEXTURE_2D_MULTISAMPLE ? GL_TEXTURE_2D : m_target;
  4476. const GLenum targetMsaa = m_target;
  4477. const uint8_t numMips = m_numMips;
  4478. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  4479. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  4480. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  4481. || s_extension[Extension::APPLE_texture_max_level].m_supported)
  4482. {
  4483. GL_CHECK(glTexParameteri(targetMsaa, GL_TEXTURE_MAX_LEVEL, numMips-1) );
  4484. }
  4485. if (target == GL_TEXTURE_3D)
  4486. {
  4487. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  4488. }
  4489. GLenum magFilter;
  4490. GLenum minFilter;
  4491. getFilters(flags, 1 < numMips, magFilter, minFilter);
  4492. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) );
  4493. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) );
  4494. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4495. || s_renderGL->m_borderColorSupport)
  4496. {
  4497. if (hasBorderColor)
  4498. {
  4499. GL_CHECK(glTexParameterfv(target, GL_TEXTURE_BORDER_COLOR, _rgba) );
  4500. }
  4501. }
  4502. if (0 != (flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  4503. && 0.0f < s_renderGL->m_maxAnisotropy)
  4504. {
  4505. GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) );
  4506. }
  4507. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  4508. || s_renderGL->m_shadowSamplersSupport)
  4509. {
  4510. const uint32_t cmpFunc = (flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  4511. if (0 == cmpFunc)
  4512. {
  4513. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  4514. }
  4515. else
  4516. {
  4517. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  4518. GL_CHECK(glTexParameteri(target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  4519. }
  4520. }
  4521. m_currentSamplerHash = hash;
  4522. }
  4523. }
  4524. void TextureGL::commit(uint32_t _stage, uint32_t _flags, const float _palette[][4])
  4525. {
  4526. const uint32_t flags = 0 == (BGFX_TEXTURE_INTERNAL_DEFAULT_SAMPLER & _flags)
  4527. ? _flags
  4528. : m_flags
  4529. ;
  4530. const uint32_t index = (flags & BGFX_TEXTURE_BORDER_COLOR_MASK) >> BGFX_TEXTURE_BORDER_COLOR_SHIFT;
  4531. GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) );
  4532. GL_CHECK(glBindTexture(m_target, m_id) );
  4533. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4534. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4535. {
  4536. // GLES2 doesn't have support for sampler object.
  4537. setSamplerState(flags, _palette[index]);
  4538. }
  4539. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4540. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) )
  4541. {
  4542. // In case that GL 2.1 sampler object is supported via extension.
  4543. if (s_renderGL->m_samplerObjectSupport)
  4544. {
  4545. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4546. }
  4547. else
  4548. {
  4549. setSamplerState(flags, _palette[index]);
  4550. }
  4551. }
  4552. else
  4553. {
  4554. // Everything else has sampler object.
  4555. s_renderGL->setSamplerState(_stage, m_numMips, flags, _palette[index]);
  4556. }
  4557. }
  4558. void TextureGL::resolve() const
  4559. {
  4560. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  4561. if (renderTarget
  4562. && 1 < m_numMips)
  4563. {
  4564. GL_CHECK(glBindTexture(m_target, m_id) );
  4565. GL_CHECK(glGenerateMipmap(m_target) );
  4566. GL_CHECK(glBindTexture(m_target, 0) );
  4567. }
  4568. }
  4569. void writeString(bx::WriterI* _writer, const char* _str)
  4570. {
  4571. bx::write(_writer, _str, (int32_t)strlen(_str) );
  4572. }
  4573. void writeStringf(bx::WriterI* _writer, const char* _format, ...)
  4574. {
  4575. char temp[512];
  4576. va_list argList;
  4577. va_start(argList, _format);
  4578. int len = bx::vsnprintf(temp, BX_COUNTOF(temp), _format, argList);
  4579. va_end(argList);
  4580. bx::write(_writer, temp, len);
  4581. }
  4582. void strins(char* _str, const char* _insert)
  4583. {
  4584. size_t len = strlen(_insert);
  4585. memmove(&_str[len], _str, strlen(_str)+1);
  4586. memcpy(_str, _insert, len);
  4587. }
  4588. void ShaderGL::create(Memory* _mem)
  4589. {
  4590. bx::MemoryReader reader(_mem->data, _mem->size);
  4591. m_hash = bx::hashMurmur2A(_mem->data, _mem->size);
  4592. uint32_t magic;
  4593. bx::read(&reader, magic);
  4594. switch (magic)
  4595. {
  4596. case BGFX_CHUNK_MAGIC_CSH: m_type = GL_COMPUTE_SHADER; break;
  4597. case BGFX_CHUNK_MAGIC_FSH: m_type = GL_FRAGMENT_SHADER; break;
  4598. case BGFX_CHUNK_MAGIC_VSH: m_type = GL_VERTEX_SHADER; break;
  4599. default:
  4600. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  4601. break;
  4602. }
  4603. uint32_t iohash;
  4604. bx::read(&reader, iohash);
  4605. uint16_t count;
  4606. bx::read(&reader, count);
  4607. BX_TRACE("%s Shader consts %d"
  4608. , BGFX_CHUNK_MAGIC_FSH == magic ? "Fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "Vertex" : "Compute"
  4609. , count
  4610. );
  4611. for (uint32_t ii = 0; ii < count; ++ii)
  4612. {
  4613. uint8_t nameSize = 0;
  4614. bx::read(&reader, nameSize);
  4615. char name[256];
  4616. bx::read(&reader, &name, nameSize);
  4617. name[nameSize] = '\0';
  4618. uint8_t type;
  4619. bx::read(&reader, type);
  4620. uint8_t num;
  4621. bx::read(&reader, num);
  4622. uint16_t regIndex;
  4623. bx::read(&reader, regIndex);
  4624. uint16_t regCount;
  4625. bx::read(&reader, regCount);
  4626. }
  4627. uint32_t shaderSize;
  4628. bx::read(&reader, shaderSize);
  4629. m_id = glCreateShader(m_type);
  4630. BX_WARN(0 != m_id, "Failed to create %s shader."
  4631. , BGFX_CHUNK_MAGIC_FSH == magic ? "fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "vertex" : "compute"
  4632. );
  4633. const char* code = (const char*)reader.getDataPtr();
  4634. if (0 != m_id)
  4635. {
  4636. if (GL_COMPUTE_SHADER != m_type)
  4637. {
  4638. int32_t codeLen = (int32_t)strlen(code);
  4639. int32_t tempLen = codeLen + (4<<10);
  4640. char* temp = (char*)alloca(tempLen);
  4641. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  4642. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  4643. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  4644. {
  4645. writeString(&writer,
  4646. "#define centroid\n"
  4647. "#define flat\n"
  4648. "#define noperspective\n"
  4649. "#define smooth\n"
  4650. );
  4651. bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported
  4652. && bx::findIdentifierMatch(code, s_OES_standard_derivatives)
  4653. ;
  4654. bool usesFragData = !!bx::findIdentifierMatch(code, "gl_FragData");
  4655. bool usesFragDepth = !!bx::findIdentifierMatch(code, "gl_FragDepth");
  4656. bool usesShadowSamplers = !!bx::findIdentifierMatch(code, s_EXT_shadow_samplers);
  4657. bool usesTexture3D = s_extension[Extension::OES_texture_3D].m_supported
  4658. && bx::findIdentifierMatch(code, s_OES_texture_3D)
  4659. ;
  4660. bool usesTextureLod = !!bx::findIdentifierMatch(code, s_EXT_shader_texture_lod);
  4661. bool usesFragmentOrdering = !!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering");
  4662. if (usesDerivatives)
  4663. {
  4664. writeString(&writer, "#extension GL_OES_standard_derivatives : enable\n");
  4665. }
  4666. if (usesFragData)
  4667. {
  4668. BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported
  4669. || s_extension[Extension::WEBGL_draw_buffers].m_supported
  4670. , "EXT_draw_buffers is used but not supported by GLES2 driver."
  4671. );
  4672. writeString(&writer
  4673. , "#extension GL_EXT_draw_buffers : enable\n"
  4674. );
  4675. }
  4676. bool insertFragDepth = false;
  4677. if (usesFragDepth)
  4678. {
  4679. BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver.");
  4680. if (s_extension[Extension::EXT_frag_depth].m_supported)
  4681. {
  4682. writeString(&writer
  4683. , "#extension GL_EXT_frag_depth : enable\n"
  4684. "#define bgfx_FragDepth gl_FragDepthEXT\n"
  4685. );
  4686. char str[128];
  4687. bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n"
  4688. , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump"
  4689. );
  4690. writeString(&writer, str);
  4691. }
  4692. else
  4693. {
  4694. insertFragDepth = true;
  4695. }
  4696. }
  4697. if (usesShadowSamplers)
  4698. {
  4699. if (s_renderGL->m_shadowSamplersSupport)
  4700. {
  4701. writeString(&writer
  4702. , "#extension GL_EXT_shadow_samplers : enable\n"
  4703. "#define shadow2D shadow2DEXT\n"
  4704. "#define shadow2DProj shadow2DProjEXT\n"
  4705. );
  4706. }
  4707. else
  4708. {
  4709. writeString(&writer
  4710. , "#define sampler2DShadow sampler2D\n"
  4711. "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n"
  4712. "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n"
  4713. );
  4714. }
  4715. }
  4716. if (usesTexture3D)
  4717. {
  4718. writeString(&writer, "#extension GL_OES_texture_3D : enable\n");
  4719. }
  4720. if (usesTextureLod)
  4721. {
  4722. BX_WARN(s_extension[Extension::EXT_shader_texture_lod].m_supported, "EXT_shader_texture_lod is used but not supported by GLES2 driver.");
  4723. if (s_extension[Extension::EXT_shader_texture_lod].m_supported
  4724. /*&& GL_VERTEX_SHADER == m_type*/)
  4725. {
  4726. writeString(&writer
  4727. , "#extension GL_EXT_shader_texture_lod : enable\n"
  4728. "#define texture2DLod texture2DLodEXT\n"
  4729. "#define texture2DProjLod texture2DProjLodEXT\n"
  4730. "#define textureCubeLod textureCubeLodEXT\n"
  4731. );
  4732. }
  4733. else
  4734. {
  4735. writeString(&writer
  4736. , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n"
  4737. "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n"
  4738. "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n"
  4739. );
  4740. }
  4741. }
  4742. if (usesFragmentOrdering)
  4743. {
  4744. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  4745. {
  4746. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  4747. }
  4748. else
  4749. {
  4750. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  4751. }
  4752. }
  4753. writeStringf(&writer, "precision %s float;\n"
  4754. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  4755. );
  4756. bx::write(&writer, code, codeLen);
  4757. bx::write(&writer, '\0');
  4758. if (insertFragDepth)
  4759. {
  4760. char* entry = strstr(temp, "void main ()");
  4761. if (NULL != entry)
  4762. {
  4763. char* brace = strstr(entry, "{");
  4764. if (NULL != brace)
  4765. {
  4766. const char* end = bx::strmb(brace, '{', '}');
  4767. if (NULL != end)
  4768. {
  4769. strins(brace+1, "\n float bgfx_FragDepth = 0.0;\n");
  4770. }
  4771. }
  4772. }
  4773. }
  4774. // Replace all instances of gl_FragDepth with bgfx_FragDepth.
  4775. for (const char* fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth"); NULL != fragDepth; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth") )
  4776. {
  4777. char* insert = const_cast<char*>(fragDepth);
  4778. strins(insert, "bg");
  4779. memcpy(insert + 2, "fx", 2);
  4780. }
  4781. }
  4782. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4783. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) )
  4784. {
  4785. const bool usesTextureLod = true
  4786. && s_extension[Extension::ARB_shader_texture_lod].m_supported
  4787. && bx::findIdentifierMatch(code, s_ARB_shader_texture_lod)
  4788. ;
  4789. const bool usesGpuShader5 = !!bx::findIdentifierMatch(code, s_ARB_gpu_shader5);
  4790. const bool usesIUsamplers = !!bx::findIdentifierMatch(code, s_uisamplers);
  4791. const bool usesTexelFetch = !!bx::findIdentifierMatch(code, s_texelFetch);
  4792. const bool usesTextureArray = !!bx::findIdentifierMatch(code, s_textureArray);
  4793. const bool usesTextureMS = !!bx::findIdentifierMatch(code, s_ARB_texture_multisample);
  4794. const bool usesPacking = !!bx::findIdentifierMatch(code, s_ARB_shading_language_packing);
  4795. uint32_t version =
  4796. usesIUsamplers || usesTexelFetch ? 130
  4797. : usesTextureLod ? 120
  4798. : 120
  4799. ;
  4800. if (0 != version)
  4801. {
  4802. writeStringf(&writer, "#version %d\n", version);
  4803. }
  4804. if (usesTextureLod)
  4805. {
  4806. if (m_type == GL_FRAGMENT_SHADER)
  4807. {
  4808. writeString(&writer, "#extension GL_ARB_shader_texture_lod : enable\n");
  4809. }
  4810. }
  4811. if (usesGpuShader5)
  4812. {
  4813. writeString(&writer, "#extension GL_ARB_gpu_shader5 : enable\n");
  4814. }
  4815. if (usesPacking)
  4816. {
  4817. writeString(&writer, "#extension GL_ARB_shading_language_packing : enable\n");
  4818. }
  4819. if (usesTextureMS)
  4820. {
  4821. writeString(&writer, "#extension GL_ARB_texture_multisample : enable\n");
  4822. }
  4823. if (usesTextureArray)
  4824. {
  4825. writeString(&writer, "#extension GL_EXT_texture_array : enable\n");
  4826. }
  4827. if (130 <= version)
  4828. {
  4829. if (m_type == GL_FRAGMENT_SHADER)
  4830. {
  4831. writeString(&writer, "#define varying in\n");
  4832. }
  4833. else
  4834. {
  4835. writeString(&writer, "#define attribute in\n");
  4836. writeString(&writer, "#define varying out\n");
  4837. }
  4838. uint32_t fragData = 0;
  4839. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  4840. {
  4841. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  4842. {
  4843. char tmpFragData[16];
  4844. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  4845. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  4846. }
  4847. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  4848. }
  4849. if (0 != fragData)
  4850. {
  4851. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  4852. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  4853. }
  4854. else
  4855. {
  4856. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  4857. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  4858. }
  4859. }
  4860. else
  4861. {
  4862. if (m_type == GL_FRAGMENT_SHADER)
  4863. {
  4864. writeString(&writer, "#define in varying\n");
  4865. }
  4866. else
  4867. {
  4868. writeString(&writer, "#define in attribute\n");
  4869. writeString(&writer, "#define out varying\n");
  4870. }
  4871. }
  4872. writeString(&writer,
  4873. "#define lowp\n"
  4874. "#define mediump\n"
  4875. "#define highp\n"
  4876. "#define centroid\n"
  4877. "#define flat\n"
  4878. "#define noperspective\n"
  4879. "#define smooth\n"
  4880. );
  4881. bx::write(&writer, code, codeLen);
  4882. bx::write(&writer, '\0');
  4883. }
  4884. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  4885. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4886. {
  4887. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4888. {
  4889. writeString(&writer
  4890. , "#version 300 es\n"
  4891. "precision mediump float;\n"
  4892. );
  4893. }
  4894. else
  4895. {
  4896. writeString(&writer, "#version 140\n");
  4897. }
  4898. writeString(&writer, "#define texture2DLod textureLod\n");
  4899. writeString(&writer, "#define texture3DLod textureLod\n");
  4900. writeString(&writer, "#define textureCubeLod textureLod\n");
  4901. if (m_type == GL_FRAGMENT_SHADER)
  4902. {
  4903. writeString(&writer, "#define varying in\n");
  4904. writeString(&writer, "#define texture2D texture\n");
  4905. writeString(&writer, "#define texture2DProj textureProj\n");
  4906. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4907. {
  4908. writeString(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4909. writeString(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n");
  4910. }
  4911. else
  4912. {
  4913. writeString(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  4914. writeString(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n");
  4915. }
  4916. writeString(&writer, "#define texture3D texture\n");
  4917. writeString(&writer, "#define textureCube texture\n");
  4918. uint32_t fragData = 0;
  4919. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  4920. {
  4921. for (uint32_t ii = 0, num = g_caps.limits.maxFBAttachments; ii < num; ++ii)
  4922. {
  4923. char tmpFragData[16];
  4924. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  4925. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  4926. }
  4927. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  4928. }
  4929. if (!!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering") )
  4930. {
  4931. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  4932. {
  4933. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  4934. }
  4935. else
  4936. {
  4937. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  4938. }
  4939. }
  4940. if (!!bx::findIdentifierMatch(code, s_ARB_texture_multisample) )
  4941. {
  4942. writeString(&writer, "#extension GL_ARB_texture_multisample : enable\n");
  4943. }
  4944. if (0 != fragData)
  4945. {
  4946. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  4947. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  4948. }
  4949. else
  4950. {
  4951. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  4952. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  4953. }
  4954. }
  4955. else
  4956. {
  4957. writeString(&writer, "#define attribute in\n");
  4958. writeString(&writer, "#define varying out\n");
  4959. }
  4960. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  4961. {
  4962. writeString(&writer
  4963. , "#define lowp\n"
  4964. "#define mediump\n"
  4965. "#define highp\n"
  4966. );
  4967. }
  4968. bx::write(&writer, code, codeLen);
  4969. bx::write(&writer, '\0');
  4970. }
  4971. code = temp;
  4972. }
  4973. GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) );
  4974. GL_CHECK(glCompileShader(m_id) );
  4975. GLint compiled = 0;
  4976. GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) );
  4977. if (0 == compiled)
  4978. {
  4979. BX_TRACE("\n####\n%s\n####", code);
  4980. GLsizei len;
  4981. char log[1024];
  4982. GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) );
  4983. BX_TRACE("Failed to compile shader. %d: %s", compiled, log);
  4984. GL_CHECK(glDeleteShader(m_id) );
  4985. m_id = 0;
  4986. BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader.");
  4987. }
  4988. else if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  4989. && s_extension[Extension::ANGLE_translated_shader_source].m_supported
  4990. && NULL != glGetTranslatedShaderSourceANGLE)
  4991. {
  4992. GLsizei len;
  4993. GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) );
  4994. char* source = (char*)alloca(len);
  4995. GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) );
  4996. BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source);
  4997. }
  4998. }
  4999. }
  5000. void ShaderGL::destroy()
  5001. {
  5002. if (0 != m_id)
  5003. {
  5004. GL_CHECK(glDeleteShader(m_id) );
  5005. m_id = 0;
  5006. }
  5007. }
  5008. static void frameBufferValidate()
  5009. {
  5010. GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  5011. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete
  5012. , "glCheckFramebufferStatus failed 0x%08x: %s"
  5013. , complete
  5014. , glEnumName(complete)
  5015. );
  5016. BX_UNUSED(complete);
  5017. }
  5018. void FrameBufferGL::create(uint8_t _num, const Attachment* _attachment)
  5019. {
  5020. GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) );
  5021. m_numTh = _num;
  5022. memcpy(m_attachment, _attachment, _num*sizeof(Attachment) );
  5023. postReset();
  5024. }
  5025. void FrameBufferGL::postReset()
  5026. {
  5027. if (0 != m_fbo[0])
  5028. {
  5029. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  5030. bool needResolve = false;
  5031. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  5032. uint32_t colorIdx = 0;
  5033. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5034. {
  5035. TextureHandle handle = m_attachment[ii].handle;
  5036. if (isValid(handle) )
  5037. {
  5038. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  5039. if (0 == colorIdx)
  5040. {
  5041. m_width = bx::uint32_max(texture.m_width >> m_attachment[ii].mip, 1);
  5042. m_height = bx::uint32_max(texture.m_height >> m_attachment[ii].mip, 1);
  5043. }
  5044. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  5045. TextureFormat::Enum format = (TextureFormat::Enum)texture.m_textureFormat;
  5046. if (isDepth(format) )
  5047. {
  5048. const ImageBlockInfo& info = getBlockInfo(format);
  5049. if (0 < info.stencilBits)
  5050. {
  5051. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  5052. }
  5053. else if (0 == info.depthBits)
  5054. {
  5055. attachment = GL_STENCIL_ATTACHMENT;
  5056. }
  5057. else
  5058. {
  5059. attachment = GL_DEPTH_ATTACHMENT;
  5060. }
  5061. }
  5062. else
  5063. {
  5064. buffers[colorIdx] = attachment;
  5065. ++colorIdx;
  5066. }
  5067. if (0 != texture.m_rbo)
  5068. {
  5069. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  5070. , attachment
  5071. , GL_RENDERBUFFER
  5072. , texture.m_rbo
  5073. ) );
  5074. }
  5075. else
  5076. {
  5077. GLenum target = texture.isCubeMap()
  5078. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + m_attachment[ii].layer
  5079. : texture.m_target
  5080. ;
  5081. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  5082. , attachment
  5083. , target
  5084. , texture.m_id
  5085. , m_attachment[ii].mip
  5086. ) );
  5087. }
  5088. needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id);
  5089. }
  5090. }
  5091. m_num = uint8_t(colorIdx);
  5092. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  5093. {
  5094. if (0 == colorIdx)
  5095. {
  5096. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  5097. {
  5098. // When only depth is attached disable draw buffer to avoid
  5099. // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER.
  5100. GL_CHECK(glDrawBuffer(GL_NONE) );
  5101. }
  5102. }
  5103. else
  5104. {
  5105. GL_CHECK(glDrawBuffers(colorIdx, buffers) );
  5106. }
  5107. // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER.
  5108. GL_CHECK(glReadBuffer(GL_NONE) );
  5109. }
  5110. frameBufferValidate();
  5111. if (needResolve)
  5112. {
  5113. GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) );
  5114. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  5115. colorIdx = 0;
  5116. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5117. {
  5118. TextureHandle handle = m_attachment[ii].handle;
  5119. if (isValid(handle) )
  5120. {
  5121. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  5122. if (0 != texture.m_id)
  5123. {
  5124. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  5125. if (!isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  5126. {
  5127. ++colorIdx;
  5128. GLenum target = texture.isCubeMap()
  5129. ? GL_TEXTURE_CUBE_MAP_POSITIVE_X + m_attachment[ii].layer
  5130. : texture.m_target
  5131. ;
  5132. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  5133. , attachment
  5134. , target
  5135. , texture.m_id
  5136. , m_attachment[ii].mip
  5137. ) );
  5138. }
  5139. }
  5140. }
  5141. }
  5142. frameBufferValidate();
  5143. }
  5144. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  5145. }
  5146. }
  5147. void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  5148. {
  5149. BX_UNUSED(_depthFormat);
  5150. m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh);
  5151. m_width = _width;
  5152. m_height = _height;
  5153. m_denseIdx = _denseIdx;
  5154. }
  5155. uint16_t FrameBufferGL::destroy()
  5156. {
  5157. if (0 != m_num)
  5158. {
  5159. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  5160. m_num = 0;
  5161. }
  5162. if (NULL != m_swapChain)
  5163. {
  5164. s_renderGL->m_glctx.destroySwapChain(m_swapChain);
  5165. m_swapChain = NULL;
  5166. }
  5167. memset(m_fbo, 0, sizeof(m_fbo) );
  5168. uint16_t denseIdx = m_denseIdx;
  5169. m_denseIdx = UINT16_MAX;
  5170. return denseIdx;
  5171. }
  5172. void FrameBufferGL::resolve()
  5173. {
  5174. if (0 != m_fbo[1])
  5175. {
  5176. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  5177. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) );
  5178. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  5179. GL_CHECK(glBlitFramebuffer(0
  5180. , 0
  5181. , m_width
  5182. , m_height
  5183. , 0
  5184. , 0
  5185. , m_width
  5186. , m_height
  5187. , GL_COLOR_BUFFER_BIT
  5188. , GL_LINEAR
  5189. ) );
  5190. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  5191. GL_CHECK(glReadBuffer(GL_NONE) );
  5192. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  5193. }
  5194. if (0 < m_numTh)
  5195. {
  5196. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  5197. {
  5198. TextureHandle handle = m_attachment[ii].handle;
  5199. if (isValid(handle) )
  5200. {
  5201. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  5202. texture.resolve();
  5203. }
  5204. }
  5205. }
  5206. }
  5207. void FrameBufferGL::discard(uint16_t _flags)
  5208. {
  5209. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2];
  5210. uint32_t idx = 0;
  5211. if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) )
  5212. {
  5213. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  5214. {
  5215. if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) )
  5216. {
  5217. buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii;
  5218. }
  5219. }
  5220. }
  5221. uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL);
  5222. if (BGFX_CLEAR_NONE != dsFlags)
  5223. {
  5224. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  5225. && (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags)
  5226. {
  5227. buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT;
  5228. }
  5229. else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags)
  5230. {
  5231. buffers[idx++] = GL_DEPTH_ATTACHMENT;
  5232. }
  5233. else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags)
  5234. {
  5235. buffers[idx++] = GL_STENCIL_ATTACHMENT;
  5236. }
  5237. }
  5238. GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) );
  5239. }
  5240. void OcclusionQueryGL::create()
  5241. {
  5242. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  5243. {
  5244. Query& query = m_query[ii];
  5245. GL_CHECK(glGenQueries(1, &query.m_id) );
  5246. }
  5247. }
  5248. void OcclusionQueryGL::destroy()
  5249. {
  5250. for (uint32_t ii = 0; ii < BX_COUNTOF(m_query); ++ii)
  5251. {
  5252. Query& query = m_query[ii];
  5253. GL_CHECK(glDeleteQueries(1, &query.m_id) );
  5254. }
  5255. }
  5256. void OcclusionQueryGL::begin(Frame* _render, OcclusionQueryHandle _handle)
  5257. {
  5258. while (0 == m_control.reserve(1) )
  5259. {
  5260. resolve(_render, true);
  5261. }
  5262. Query& query = m_query[m_control.m_current];
  5263. GL_CHECK(glBeginQuery(GL_SAMPLES_PASSED, query.m_id) );
  5264. query.m_handle = _handle;
  5265. }
  5266. void OcclusionQueryGL::end()
  5267. {
  5268. GL_CHECK(glEndQuery(GL_SAMPLES_PASSED) );
  5269. m_control.commit(1);
  5270. }
  5271. void OcclusionQueryGL::resolve(Frame* _render, bool _wait)
  5272. {
  5273. while (0 != m_control.available() )
  5274. {
  5275. Query& query = m_query[m_control.m_read];
  5276. int32_t result;
  5277. if (!_wait)
  5278. {
  5279. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT_AVAILABLE, &result) );
  5280. if (!result)
  5281. {
  5282. break;
  5283. }
  5284. }
  5285. GL_CHECK(glGetQueryObjectiv(query.m_id, GL_QUERY_RESULT, &result) );
  5286. _render->m_occlusion[query.m_handle.idx] = 0 < result;
  5287. m_control.consume(1);
  5288. }
  5289. }
  5290. void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  5291. {
  5292. BGFX_GPU_PROFILER_BEGIN_DYNAMIC("rendererSubmit");
  5293. if (_render->m_capture)
  5294. {
  5295. renderDocTriggerCapture();
  5296. }
  5297. if (1 < m_numWindows
  5298. && m_vaoSupport)
  5299. {
  5300. m_vaoSupport = false;
  5301. GL_CHECK(glBindVertexArray(0) );
  5302. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  5303. m_vao = 0;
  5304. m_vaoStateCache.invalidate();
  5305. }
  5306. m_glctx.makeCurrent(NULL);
  5307. const GLuint defaultVao = m_vao;
  5308. if (0 != defaultVao)
  5309. {
  5310. GL_CHECK(glBindVertexArray(defaultVao) );
  5311. }
  5312. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  5313. updateResolution(_render->m_resolution);
  5314. int64_t elapsed = -bx::getHPCounter();
  5315. int64_t captureElapsed = 0;
  5316. if (m_timerQuerySupport)
  5317. {
  5318. m_gpuTimer.begin();
  5319. }
  5320. if (0 < _render->m_iboffset)
  5321. {
  5322. TransientIndexBuffer* ib = _render->m_transientIb;
  5323. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data, true);
  5324. }
  5325. if (0 < _render->m_vboffset)
  5326. {
  5327. TransientVertexBuffer* vb = _render->m_transientVb;
  5328. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data, true);
  5329. }
  5330. _render->sort();
  5331. RenderDraw currentState;
  5332. currentState.clear();
  5333. currentState.m_stateFlags = BGFX_STATE_NONE;
  5334. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  5335. _render->m_hmdInitialized = m_ovr.isInitialized();
  5336. const bool hmdEnabled = m_ovr.isEnabled();
  5337. static ViewState viewState;
  5338. viewState.reset(_render, hmdEnabled);
  5339. uint16_t programIdx = invalidHandle;
  5340. SortKey key;
  5341. uint16_t view = UINT16_MAX;
  5342. FrameBufferHandle fbh = { BGFX_CONFIG_MAX_FRAME_BUFFERS };
  5343. BlitKey blitKey;
  5344. blitKey.decode(_render->m_blitKeys[0]);
  5345. uint16_t numBlitItems = _render->m_numBlitItems;
  5346. uint16_t blitItem = 0;
  5347. int32_t resolutionHeight = hmdEnabled
  5348. ? _render->m_hmd.height
  5349. : _render->m_resolution.m_height
  5350. ;
  5351. uint32_t blendFactor = 0;
  5352. uint8_t primIndex;
  5353. {
  5354. const uint64_t pt = 0;
  5355. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  5356. }
  5357. PrimInfo prim = s_primInfo[primIndex];
  5358. GL_CHECK(glPolygonMode(GL_FRONT_AND_BACK
  5359. , _render->m_debug&BGFX_DEBUG_WIREFRAME
  5360. ? GL_LINE
  5361. : GL_FILL
  5362. ) );
  5363. uint32_t baseVertex = 0;
  5364. GLuint currentVao = 0;
  5365. bool wasCompute = false;
  5366. bool viewHasScissor = false;
  5367. Rect viewScissorRect;
  5368. viewScissorRect.clear();
  5369. uint16_t discardFlags = BGFX_CLEAR_NONE;
  5370. const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported;
  5371. const bool computeSupported = (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported)
  5372. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  5373. ;
  5374. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  5375. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  5376. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  5377. uint32_t statsNumIndices = 0;
  5378. uint32_t statsKeyType[2] = {};
  5379. if (m_occlusionQuerySupport)
  5380. {
  5381. m_occlusionQuery.resolve(_render);
  5382. }
  5383. uint8_t eye = 0;
  5384. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  5385. {
  5386. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  5387. bool viewRestart = false;
  5388. uint8_t restartState = 0;
  5389. viewState.m_rect = _render->m_rect[0];
  5390. int32_t numItems = _render->m_num;
  5391. for (int32_t item = 0, restartItem = numItems; item < numItems || restartItem < numItems;)
  5392. {
  5393. const bool isCompute = key.decode(_render->m_sortKeys[item], _render->m_viewRemap);
  5394. statsKeyType[isCompute]++;
  5395. const bool viewChanged = 0
  5396. || key.m_view != view
  5397. || item == numItems
  5398. ;
  5399. const RenderItem& renderItem = _render->m_renderItem[_render->m_sortValues[item] ];
  5400. ++item;
  5401. if (viewChanged)
  5402. {
  5403. if (1 == restartState)
  5404. {
  5405. restartState = 2;
  5406. item = restartItem;
  5407. restartItem = numItems;
  5408. view = UINT16_MAX;
  5409. continue;
  5410. }
  5411. view = key.m_view;
  5412. programIdx = invalidHandle;
  5413. if (_render->m_fb[view].idx != fbh.idx)
  5414. {
  5415. fbh = _render->m_fb[view];
  5416. resolutionHeight = hmdEnabled
  5417. ? _render->m_hmd.height
  5418. : _render->m_resolution.m_height
  5419. ;
  5420. resolutionHeight = setFrameBuffer(fbh, resolutionHeight, discardFlags);
  5421. }
  5422. viewRestart = ( (BGFX_VIEW_STEREO == (_render->m_viewFlags[view] & BGFX_VIEW_STEREO) ) );
  5423. viewRestart &= hmdEnabled;
  5424. if (viewRestart)
  5425. {
  5426. if (0 == restartState)
  5427. {
  5428. restartState = 1;
  5429. restartItem = item - 1;
  5430. }
  5431. eye = (restartState - 1) & 1;
  5432. restartState &= 1;
  5433. }
  5434. else
  5435. {
  5436. eye = 0;
  5437. }
  5438. if (item > 1)
  5439. {
  5440. BGFX_GPU_PROFILER_END();
  5441. BGFX_PROFILER_END();
  5442. }
  5443. BGFX_PROFILER_BEGIN_DYNAMIC(s_viewName[view]);
  5444. BGFX_GPU_PROFILER_BEGIN_DYNAMIC(s_viewName[view]);
  5445. viewState.m_rect = _render->m_rect[view];
  5446. if (viewRestart)
  5447. {
  5448. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5449. {
  5450. char* viewName = s_viewName[view];
  5451. viewName[3] = ' ';
  5452. viewName[4] = eye ? 'R' : 'L';
  5453. GL_CHECK(glInsertEventMarker(0, viewName) );
  5454. }
  5455. if (m_ovr.isEnabled() )
  5456. {
  5457. m_ovr.renderEyeStart(eye, &viewState.m_rect);
  5458. }
  5459. else
  5460. {
  5461. viewState.m_rect.m_x = eye * (viewState.m_rect.m_width+1)/2;
  5462. viewState.m_rect.m_width /= 2;
  5463. }
  5464. }
  5465. else
  5466. {
  5467. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5468. {
  5469. char* viewName = s_viewName[view];
  5470. viewName[3] = ' ';
  5471. viewName[4] = ' ';
  5472. GL_CHECK(glInsertEventMarker(0, viewName) );
  5473. }
  5474. }
  5475. const Rect& scissorRect = _render->m_scissor[view];
  5476. viewHasScissor = !scissorRect.isZero();
  5477. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  5478. GL_CHECK(glViewport(viewState.m_rect.m_x
  5479. , resolutionHeight-viewState.m_rect.m_height-viewState.m_rect.m_y
  5480. , viewState.m_rect.m_width
  5481. , viewState.m_rect.m_height
  5482. ) );
  5483. Clear& clear = _render->m_clear[view];
  5484. discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK;
  5485. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  5486. {
  5487. clearQuad(_clearQuad, viewState.m_rect, clear, resolutionHeight, _render->m_colorPalette);
  5488. currentVao = UINT32_MAX; // clearQuad will mess with VAO, invalidate it.
  5489. }
  5490. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  5491. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5492. GL_CHECK(glDepthFunc(GL_LESS) );
  5493. GL_CHECK(glEnable(GL_CULL_FACE) );
  5494. GL_CHECK(glDisable(GL_BLEND) );
  5495. if (m_blitSupported)
  5496. {
  5497. for (; blitItem < numBlitItems && blitKey.m_view <= view; blitItem++)
  5498. {
  5499. const BlitItem& bi = _render->m_blitItem[blitItem];
  5500. blitKey.decode(_render->m_blitKeys[blitItem + 1]);
  5501. const TextureGL& src = m_textures[bi.m_src.idx];
  5502. const TextureGL& dst = m_textures[bi.m_dst.idx];
  5503. uint32_t srcWidth = bx::uint32_min(src.m_width, bi.m_srcX + bi.m_width) - bi.m_srcX;
  5504. uint32_t srcHeight = bx::uint32_min(src.m_height, bi.m_srcY + bi.m_height) - bi.m_srcY;
  5505. uint32_t srcDepth = bx::uint32_min(src.m_depth, bi.m_srcZ + bi.m_depth) - bi.m_srcZ;
  5506. uint32_t dstWidth = bx::uint32_min(dst.m_width, bi.m_dstX + bi.m_width) - bi.m_dstX;
  5507. uint32_t dstHeight = bx::uint32_min(dst.m_height, bi.m_dstY + bi.m_height) - bi.m_dstY;
  5508. uint32_t dstDepth = bx::uint32_min(dst.m_depth, bi.m_dstZ + bi.m_depth) - bi.m_dstZ;
  5509. uint32_t width = bx::uint32_min(srcWidth, dstWidth);
  5510. uint32_t height = bx::uint32_min(srcHeight, dstHeight);
  5511. uint32_t depth = bx::uint32_min(srcDepth, dstDepth);
  5512. GL_CHECK(glCopyImageSubData(src.m_id
  5513. , src.m_target
  5514. , bi.m_srcMip
  5515. , bi.m_srcX
  5516. , bi.m_srcY
  5517. , bi.m_srcZ
  5518. , dst.m_id
  5519. , dst.m_target
  5520. , bi.m_dstMip
  5521. , bi.m_dstX
  5522. , bi.m_dstY
  5523. , bi.m_dstZ
  5524. , width
  5525. , height
  5526. , bx::uint32_imax(depth, 1)
  5527. ) );
  5528. }
  5529. }
  5530. }
  5531. if (isCompute)
  5532. {
  5533. if (!wasCompute)
  5534. {
  5535. wasCompute = true;
  5536. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5537. {
  5538. char* viewName = s_viewName[view];
  5539. viewName[3] = 'C';
  5540. GL_CHECK(glInsertEventMarker(0, viewName) );
  5541. }
  5542. }
  5543. if (computeSupported)
  5544. {
  5545. const RenderCompute& compute = renderItem.compute;
  5546. ProgramGL& program = m_program[key.m_program];
  5547. GL_CHECK(glUseProgram(program.m_id) );
  5548. GLbitfield barrier = 0;
  5549. for (uint32_t ii = 0; ii < BGFX_MAX_COMPUTE_BINDINGS; ++ii)
  5550. {
  5551. const Binding& bind = compute.m_bind[ii];
  5552. if (invalidHandle != bind.m_idx)
  5553. {
  5554. switch (bind.m_type)
  5555. {
  5556. case Binding::Image:
  5557. {
  5558. const TextureGL& texture = m_textures[bind.m_idx];
  5559. GL_CHECK(glBindImageTexture(ii
  5560. , texture.m_id
  5561. , bind.m_un.m_compute.m_mip
  5562. , texture.isCubeMap()?GL_TRUE:GL_FALSE
  5563. , 0
  5564. , s_access[bind.m_un.m_compute.m_access]
  5565. , s_imageFormat[bind.m_un.m_compute.m_format])
  5566. );
  5567. barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  5568. }
  5569. break;
  5570. case Binding::IndexBuffer:
  5571. {
  5572. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  5573. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5574. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5575. }
  5576. break;
  5577. case Binding::VertexBuffer:
  5578. {
  5579. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  5580. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id) );
  5581. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  5582. }
  5583. break;
  5584. }
  5585. }
  5586. }
  5587. if (0 != barrier)
  5588. {
  5589. bool constantsChanged = compute.m_constBegin < compute.m_constEnd;
  5590. rendererUpdateUniforms(this, _render->m_uniformBuffer, compute.m_constBegin, compute.m_constEnd);
  5591. if (constantsChanged
  5592. && NULL != program.m_constantBuffer)
  5593. {
  5594. commit(*program.m_constantBuffer);
  5595. }
  5596. viewState.setPredefined<1>(this, view, eye, program, _render, compute);
  5597. if (isValid(compute.m_indirectBuffer) )
  5598. {
  5599. const VertexBufferGL& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  5600. if (currentState.m_indirectBuffer.idx != compute.m_indirectBuffer.idx)
  5601. {
  5602. currentState.m_indirectBuffer = compute.m_indirectBuffer;
  5603. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, vb.m_id) );
  5604. }
  5605. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  5606. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  5607. : compute.m_numIndirect
  5608. ;
  5609. uintptr_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5610. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  5611. {
  5612. GL_CHECK(glDispatchComputeIndirect( (GLintptr)args) );
  5613. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  5614. }
  5615. }
  5616. else
  5617. {
  5618. if (isValid(currentState.m_indirectBuffer) )
  5619. {
  5620. currentState.m_indirectBuffer.idx = invalidHandle;
  5621. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0) );
  5622. }
  5623. GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) );
  5624. }
  5625. GL_CHECK(glMemoryBarrier(barrier) );
  5626. }
  5627. }
  5628. continue;
  5629. }
  5630. bool resetState = viewChanged || wasCompute;
  5631. if (wasCompute)
  5632. {
  5633. wasCompute = false;
  5634. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  5635. {
  5636. char* viewName = s_viewName[view];
  5637. viewName[3] = ' ';
  5638. GL_CHECK(glInsertEventMarker(0, viewName) );
  5639. }
  5640. }
  5641. const RenderDraw& draw = renderItem.draw;
  5642. const bool hasOcclusionQuery = 0 != (draw.m_stateFlags & BGFX_STATE_INTERNAL_OCCLUSION_QUERY);
  5643. if (isValid(draw.m_occlusionQuery)
  5644. && !hasOcclusionQuery
  5645. && !isVisible(_render, draw.m_occlusionQuery, 0 != (draw.m_submitFlags&BGFX_SUBMIT_INTERNAL_OCCLUSION_VISIBLE) ) )
  5646. {
  5647. continue;
  5648. }
  5649. const uint64_t newFlags = draw.m_stateFlags;
  5650. uint64_t changedFlags = currentState.m_stateFlags ^ draw.m_stateFlags;
  5651. currentState.m_stateFlags = newFlags;
  5652. const uint64_t newStencil = draw.m_stencil;
  5653. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  5654. currentState.m_stencil = newStencil;
  5655. if (resetState)
  5656. {
  5657. currentState.clear();
  5658. currentState.m_scissor = !draw.m_scissor;
  5659. changedFlags = BGFX_STATE_MASK;
  5660. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  5661. currentState.m_stateFlags = newFlags;
  5662. currentState.m_stencil = newStencil;
  5663. }
  5664. uint16_t scissor = draw.m_scissor;
  5665. if (currentState.m_scissor != scissor)
  5666. {
  5667. currentState.m_scissor = scissor;
  5668. if (UINT16_MAX == scissor)
  5669. {
  5670. if (viewHasScissor)
  5671. {
  5672. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5673. GL_CHECK(glScissor(viewScissorRect.m_x
  5674. , resolutionHeight-viewScissorRect.m_height-viewScissorRect.m_y
  5675. , viewScissorRect.m_width
  5676. , viewScissorRect.m_height
  5677. ) );
  5678. }
  5679. else
  5680. {
  5681. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  5682. }
  5683. }
  5684. else
  5685. {
  5686. Rect scissorRect;
  5687. scissorRect.intersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  5688. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  5689. GL_CHECK(glScissor(scissorRect.m_x
  5690. , resolutionHeight-scissorRect.m_height-scissorRect.m_y
  5691. , scissorRect.m_width
  5692. , scissorRect.m_height
  5693. ) );
  5694. }
  5695. }
  5696. if (0 != changedStencil)
  5697. {
  5698. if (0 != newStencil)
  5699. {
  5700. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  5701. uint32_t bstencil = unpackStencil(1, newStencil);
  5702. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  5703. // uint32_t bchanged = unpackStencil(1, changedStencil);
  5704. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  5705. // {
  5706. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5707. // GL_CHECK(glStencilMask(wmask) );
  5708. // }
  5709. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  5710. {
  5711. uint32_t stencil = unpackStencil(ii, newStencil);
  5712. uint32_t changed = unpackStencil(ii, changedStencil);
  5713. GLenum face = s_stencilFace[frontAndBack+ii];
  5714. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  5715. {
  5716. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  5717. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  5718. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  5719. GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask) );
  5720. }
  5721. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  5722. {
  5723. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  5724. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  5725. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  5726. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  5727. }
  5728. }
  5729. }
  5730. else
  5731. {
  5732. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  5733. }
  5734. }
  5735. if ( (0
  5736. | BGFX_STATE_CULL_MASK
  5737. | BGFX_STATE_DEPTH_WRITE
  5738. | BGFX_STATE_DEPTH_TEST_MASK
  5739. | BGFX_STATE_RGB_WRITE
  5740. | BGFX_STATE_ALPHA_WRITE
  5741. | BGFX_STATE_BLEND_MASK
  5742. | BGFX_STATE_BLEND_EQUATION_MASK
  5743. | BGFX_STATE_ALPHA_REF_MASK
  5744. | BGFX_STATE_PT_MASK
  5745. | BGFX_STATE_POINT_SIZE_MASK
  5746. | BGFX_STATE_MSAA
  5747. | BGFX_STATE_LINEAA
  5748. | BGFX_STATE_CONSERVATIVE_RASTER
  5749. ) & changedFlags)
  5750. {
  5751. if (BGFX_STATE_CULL_MASK & changedFlags)
  5752. {
  5753. if (BGFX_STATE_CULL_CW & newFlags)
  5754. {
  5755. GL_CHECK(glEnable(GL_CULL_FACE) );
  5756. GL_CHECK(glCullFace(GL_BACK) );
  5757. }
  5758. else if (BGFX_STATE_CULL_CCW & newFlags)
  5759. {
  5760. GL_CHECK(glEnable(GL_CULL_FACE) );
  5761. GL_CHECK(glCullFace(GL_FRONT) );
  5762. }
  5763. else
  5764. {
  5765. GL_CHECK(glDisable(GL_CULL_FACE) );
  5766. }
  5767. }
  5768. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  5769. {
  5770. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  5771. }
  5772. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  5773. {
  5774. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  5775. if (0 != func)
  5776. {
  5777. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5778. GL_CHECK(glDepthFunc(s_cmpFunc[func]) );
  5779. }
  5780. else
  5781. {
  5782. if (BGFX_STATE_DEPTH_WRITE & newFlags)
  5783. {
  5784. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  5785. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  5786. }
  5787. else
  5788. {
  5789. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  5790. }
  5791. }
  5792. }
  5793. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  5794. {
  5795. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  5796. viewState.m_alphaRef = ref/255.0f;
  5797. }
  5798. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  5799. {
  5800. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  5801. {
  5802. float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  5803. GL_CHECK(glPointSize(pointSize) );
  5804. }
  5805. if (BGFX_STATE_MSAA & changedFlags)
  5806. {
  5807. GL_CHECK(BGFX_STATE_MSAA & newFlags
  5808. ? glEnable(GL_MULTISAMPLE)
  5809. : glDisable(GL_MULTISAMPLE)
  5810. );
  5811. }
  5812. if (BGFX_STATE_LINEAA & changedFlags)
  5813. {
  5814. GL_CHECK(BGFX_STATE_LINEAA & newFlags
  5815. ? glEnable(GL_LINE_SMOOTH)
  5816. : glDisable(GL_LINE_SMOOTH)
  5817. );
  5818. }
  5819. if (m_conservativeRasterSupport
  5820. && BGFX_STATE_CONSERVATIVE_RASTER & changedFlags)
  5821. {
  5822. GL_CHECK(BGFX_STATE_CONSERVATIVE_RASTER & newFlags
  5823. ? glEnable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5824. : glDisable(GL_CONSERVATIVE_RASTERIZATION_NV)
  5825. );
  5826. }
  5827. }
  5828. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  5829. {
  5830. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  5831. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  5832. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  5833. }
  5834. if ( ( (0
  5835. | BGFX_STATE_BLEND_MASK
  5836. | BGFX_STATE_BLEND_EQUATION_MASK
  5837. | BGFX_STATE_BLEND_INDEPENDENT
  5838. | BGFX_STATE_BLEND_ALPHA_TO_COVERAGE
  5839. ) & changedFlags)
  5840. || blendFactor != draw.m_rgba)
  5841. {
  5842. if (m_atocSupport)
  5843. {
  5844. if (BGFX_STATE_BLEND_ALPHA_TO_COVERAGE & newFlags)
  5845. {
  5846. GL_CHECK(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  5847. }
  5848. else
  5849. {
  5850. GL_CHECK(glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE) );
  5851. }
  5852. }
  5853. if ( ( (0
  5854. | BGFX_STATE_BLEND_MASK
  5855. | BGFX_STATE_BLEND_EQUATION_MASK
  5856. | BGFX_STATE_BLEND_INDEPENDENT) & newFlags)
  5857. || blendFactor != draw.m_rgba)
  5858. {
  5859. const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  5860. const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags)
  5861. && blendIndependentSupported
  5862. ;
  5863. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  5864. const uint32_t srcRGB = (blend )&0xf;
  5865. const uint32_t dstRGB = (blend>> 4)&0xf;
  5866. const uint32_t srcA = (blend>> 8)&0xf;
  5867. const uint32_t dstA = (blend>>12)&0xf;
  5868. const uint32_t equ = uint32_t( (newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  5869. const uint32_t equRGB = (equ )&0x7;
  5870. const uint32_t equA = (equ>>3)&0x7;
  5871. const uint32_t numRt = getNumRt();
  5872. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  5873. || 1 >= numRt
  5874. || !independent)
  5875. {
  5876. if (enabled)
  5877. {
  5878. GL_CHECK(glEnable(GL_BLEND) );
  5879. GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src
  5880. , s_blendFactor[dstRGB].m_dst
  5881. , s_blendFactor[srcA].m_src
  5882. , s_blendFactor[dstA].m_dst
  5883. ) );
  5884. GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) );
  5885. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  5886. && blendFactor != draw.m_rgba)
  5887. {
  5888. const uint32_t rgba = draw.m_rgba;
  5889. GLclampf rr = ( (rgba>>24) )/255.0f;
  5890. GLclampf gg = ( (rgba>>16)&0xff)/255.0f;
  5891. GLclampf bb = ( (rgba>> 8)&0xff)/255.0f;
  5892. GLclampf aa = ( (rgba )&0xff)/255.0f;
  5893. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  5894. }
  5895. }
  5896. else
  5897. {
  5898. GL_CHECK(glDisable(GL_BLEND) );
  5899. }
  5900. }
  5901. else
  5902. {
  5903. if (enabled)
  5904. {
  5905. GL_CHECK(glEnablei(GL_BLEND, 0) );
  5906. GL_CHECK(glBlendFuncSeparatei(0
  5907. , s_blendFactor[srcRGB].m_src
  5908. , s_blendFactor[dstRGB].m_dst
  5909. , s_blendFactor[srcA].m_src
  5910. , s_blendFactor[dstA].m_dst
  5911. ) );
  5912. GL_CHECK(glBlendEquationSeparatei(0
  5913. , s_blendEquation[equRGB]
  5914. , s_blendEquation[equA]
  5915. ) );
  5916. }
  5917. else
  5918. {
  5919. GL_CHECK(glDisablei(GL_BLEND, 0) );
  5920. }
  5921. for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11)
  5922. {
  5923. if (0 != (rgba&0x7ff) )
  5924. {
  5925. const uint32_t src = (rgba )&0xf;
  5926. const uint32_t dst = (rgba>>4)&0xf;
  5927. const uint32_t equation = (rgba>>8)&0x7;
  5928. GL_CHECK(glEnablei(GL_BLEND, ii) );
  5929. GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  5930. GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) );
  5931. }
  5932. else
  5933. {
  5934. GL_CHECK(glDisablei(GL_BLEND, ii) );
  5935. }
  5936. }
  5937. }
  5938. }
  5939. else
  5940. {
  5941. GL_CHECK(glDisable(GL_BLEND) );
  5942. }
  5943. blendFactor = draw.m_rgba;
  5944. }
  5945. const uint64_t pt = newFlags&BGFX_STATE_PT_MASK;
  5946. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  5947. prim = s_primInfo[primIndex];
  5948. }
  5949. bool programChanged = false;
  5950. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  5951. bool bindAttribs = false;
  5952. rendererUpdateUniforms(this, _render->m_uniformBuffer, draw.m_constBegin, draw.m_constEnd);
  5953. if (key.m_program != programIdx)
  5954. {
  5955. programIdx = key.m_program;
  5956. GLuint id = invalidHandle == programIdx ? 0 : m_program[programIdx].m_id;
  5957. // Skip rendering if program index is valid, but program is invalid.
  5958. programIdx = 0 == id ? invalidHandle : programIdx;
  5959. GL_CHECK(glUseProgram(id) );
  5960. programChanged =
  5961. constantsChanged =
  5962. bindAttribs = true;
  5963. }
  5964. if (invalidHandle != programIdx)
  5965. {
  5966. ProgramGL& program = m_program[programIdx];
  5967. if (constantsChanged
  5968. && NULL != program.m_constantBuffer)
  5969. {
  5970. commit(*program.m_constantBuffer);
  5971. }
  5972. viewState.setPredefined<1>(this, view, eye, program, _render, draw);
  5973. {
  5974. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  5975. {
  5976. const Binding& bind = draw.m_bind[stage];
  5977. Binding& current = currentState.m_bind[stage];
  5978. if (current.m_idx != bind.m_idx
  5979. || current.m_un.m_draw.m_textureFlags != bind.m_un.m_draw.m_textureFlags
  5980. || programChanged)
  5981. {
  5982. if (invalidHandle != bind.m_idx)
  5983. {
  5984. TextureGL& texture = m_textures[bind.m_idx];
  5985. texture.commit(stage, bind.m_un.m_draw.m_textureFlags, _render->m_colorPalette);
  5986. }
  5987. }
  5988. current = bind;
  5989. }
  5990. }
  5991. if (0 != defaultVao
  5992. && 0 == draw.m_stream[0].m_startVertex
  5993. && 0 == draw.m_instanceDataOffset)
  5994. {
  5995. if (programChanged
  5996. || baseVertex != draw.m_stream[0].m_startVertex
  5997. || currentState.m_streamMask != draw.m_streamMask
  5998. || currentState.m_stream[0].m_handle.idx != draw.m_stream[0].m_handle.idx
  5999. || currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx
  6000. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  6001. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  6002. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx)
  6003. {
  6004. bx::HashMurmur2A murmur;
  6005. murmur.begin();
  6006. const Stream& stream = draw.m_stream[0];
  6007. murmur.add(stream.m_handle.idx);
  6008. if (isValid(stream.m_handle) )
  6009. {
  6010. const VertexBufferGL& vb = m_vertexBuffers[stream.m_handle.idx];
  6011. uint16_t decl = !isValid(vb.m_decl) ? stream.m_decl.idx : vb.m_decl.idx;
  6012. murmur.add(decl);
  6013. }
  6014. murmur.add(draw.m_indexBuffer.idx);
  6015. murmur.add(draw.m_instanceDataBuffer.idx);
  6016. murmur.add(draw.m_instanceDataOffset);
  6017. murmur.add(draw.m_instanceDataStride);
  6018. murmur.add(programIdx);
  6019. uint32_t hash = murmur.end();
  6020. currentState.m_streamMask = draw.m_streamMask;
  6021. currentState.m_stream[0].m_handle = stream.m_handle;
  6022. baseVertex = stream.m_startVertex;
  6023. currentState.m_indexBuffer = draw.m_indexBuffer;
  6024. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  6025. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  6026. GLuint id = m_vaoStateCache.find(hash);
  6027. if (UINT32_MAX != id)
  6028. {
  6029. currentVao = id;
  6030. GL_CHECK(glBindVertexArray(id) );
  6031. }
  6032. else
  6033. {
  6034. id = m_vaoStateCache.add(hash);
  6035. currentVao = id;
  6036. GL_CHECK(glBindVertexArray(id) );
  6037. program.add(hash);
  6038. if (isValid(stream.m_handle) )
  6039. {
  6040. VertexBufferGL& vb = m_vertexBuffers[stream.m_handle.idx];
  6041. vb.add(hash);
  6042. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  6043. uint16_t decl = !isValid(vb.m_decl) ? stream.m_decl.idx : vb.m_decl.idx;
  6044. program.bindAttributes(m_vertexDecls[decl], stream.m_startVertex);
  6045. if (isValid(draw.m_instanceDataBuffer) )
  6046. {
  6047. VertexBufferGL& instanceVb = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  6048. instanceVb.add(hash);
  6049. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  6050. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  6051. }
  6052. }
  6053. else
  6054. {
  6055. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  6056. }
  6057. if (isValid(draw.m_indexBuffer) )
  6058. {
  6059. IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6060. ib.add(hash);
  6061. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  6062. }
  6063. else
  6064. {
  6065. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  6066. }
  6067. }
  6068. }
  6069. }
  6070. else
  6071. {
  6072. if (0 != defaultVao
  6073. && 0 != currentVao)
  6074. {
  6075. GL_CHECK(glBindVertexArray(defaultVao) );
  6076. currentState.m_streamMask = 0;
  6077. currentState.m_stream[0].m_handle.idx = invalidHandle;
  6078. currentState.m_indexBuffer.idx = invalidHandle;
  6079. bindAttribs = true;
  6080. currentVao = 0;
  6081. }
  6082. if (programChanged
  6083. || currentState.m_streamMask != draw.m_streamMask
  6084. || currentState.m_stream[0].m_handle.idx != draw.m_stream[0].m_handle.idx
  6085. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  6086. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  6087. || currentState.m_instanceDataStride != draw.m_instanceDataStride)
  6088. {
  6089. currentState.m_streamMask = draw.m_streamMask;
  6090. currentState.m_stream[0].m_handle = draw.m_stream[0].m_handle;
  6091. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  6092. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  6093. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  6094. uint16_t handle = draw.m_stream[0].m_handle.idx;
  6095. if (invalidHandle != handle)
  6096. {
  6097. VertexBufferGL& vb = m_vertexBuffers[handle];
  6098. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  6099. bindAttribs = true;
  6100. }
  6101. else
  6102. {
  6103. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  6104. }
  6105. }
  6106. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  6107. {
  6108. currentState.m_indexBuffer = draw.m_indexBuffer;
  6109. uint16_t handle = draw.m_indexBuffer.idx;
  6110. if (invalidHandle != handle)
  6111. {
  6112. IndexBufferGL& ib = m_indexBuffers[handle];
  6113. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  6114. }
  6115. else
  6116. {
  6117. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  6118. }
  6119. }
  6120. if (0 != currentState.m_streamMask)
  6121. {
  6122. if (baseVertex != draw.m_stream[0].m_startVertex
  6123. || bindAttribs)
  6124. {
  6125. baseVertex = draw.m_stream[0].m_startVertex;
  6126. const VertexBufferGL& vb = m_vertexBuffers[draw.m_stream[0].m_handle.idx];
  6127. uint16_t decl = !isValid(vb.m_decl) ? draw.m_stream[0].m_decl.idx : vb.m_decl.idx;
  6128. program.bindAttributes(m_vertexDecls[decl], draw.m_stream[0].m_startVertex);
  6129. if (isValid(draw.m_instanceDataBuffer) )
  6130. {
  6131. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) );
  6132. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  6133. }
  6134. }
  6135. }
  6136. }
  6137. if (0 != currentState.m_streamMask)
  6138. {
  6139. uint32_t numVertices = draw.m_numVertices;
  6140. if (UINT32_MAX == numVertices)
  6141. {
  6142. const VertexBufferGL& vb = m_vertexBuffers[currentState.m_stream[0].m_handle.idx];
  6143. uint16_t decl = !isValid(vb.m_decl) ? draw.m_stream[0].m_decl.idx : vb.m_decl.idx;
  6144. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  6145. numVertices = vb.m_size/vertexDecl.m_stride;
  6146. }
  6147. uint32_t numIndices = 0;
  6148. uint32_t numPrimsSubmitted = 0;
  6149. uint32_t numInstances = 0;
  6150. uint32_t numPrimsRendered = 0;
  6151. uint32_t numDrawIndirect = 0;
  6152. if (hasOcclusionQuery)
  6153. {
  6154. m_occlusionQuery.begin(_render, draw.m_occlusionQuery);
  6155. }
  6156. if (isValid(draw.m_indirectBuffer) )
  6157. {
  6158. const VertexBufferGL& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  6159. if (currentState.m_indirectBuffer.idx != draw.m_indirectBuffer.idx)
  6160. {
  6161. currentState.m_indirectBuffer = draw.m_indirectBuffer;
  6162. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, vb.m_id) );
  6163. }
  6164. if (isValid(draw.m_indexBuffer) )
  6165. {
  6166. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6167. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  6168. const GLenum indexFormat = hasIndex16
  6169. ? GL_UNSIGNED_SHORT
  6170. : GL_UNSIGNED_INT
  6171. ;
  6172. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  6173. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6174. : draw.m_numIndirect
  6175. ;
  6176. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  6177. GL_CHECK(glMultiDrawElementsIndirect(prim.m_type, indexFormat
  6178. , (void*)args
  6179. , numDrawIndirect
  6180. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6181. ) );
  6182. }
  6183. else
  6184. {
  6185. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  6186. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6187. : draw.m_numIndirect
  6188. ;
  6189. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  6190. GL_CHECK(glMultiDrawArraysIndirect(prim.m_type
  6191. , (void*)args
  6192. , numDrawIndirect
  6193. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  6194. ) );
  6195. }
  6196. }
  6197. else
  6198. {
  6199. if (isValid(currentState.m_indirectBuffer) )
  6200. {
  6201. currentState.m_indirectBuffer.idx = invalidHandle;
  6202. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) );
  6203. }
  6204. if (isValid(draw.m_indexBuffer) )
  6205. {
  6206. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  6207. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  6208. const uint32_t indexSize = hasIndex16 ? 2 : 4;
  6209. const GLenum indexFormat = hasIndex16
  6210. ? GL_UNSIGNED_SHORT
  6211. : GL_UNSIGNED_INT
  6212. ;
  6213. if (UINT32_MAX == draw.m_numIndices)
  6214. {
  6215. numIndices = ib.m_size/indexSize;
  6216. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  6217. numInstances = draw.m_numInstances;
  6218. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6219. GL_CHECK(glDrawElementsInstanced(prim.m_type
  6220. , numIndices
  6221. , indexFormat
  6222. , (void*)0
  6223. , draw.m_numInstances
  6224. ) );
  6225. }
  6226. else if (prim.m_min <= draw.m_numIndices)
  6227. {
  6228. numIndices = draw.m_numIndices;
  6229. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  6230. numInstances = draw.m_numInstances;
  6231. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6232. GL_CHECK(glDrawElementsInstanced(prim.m_type
  6233. , numIndices
  6234. , indexFormat
  6235. , (void*)(uintptr_t)(draw.m_startIndex*indexSize)
  6236. , draw.m_numInstances
  6237. ) );
  6238. }
  6239. }
  6240. else
  6241. {
  6242. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  6243. numInstances = draw.m_numInstances;
  6244. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  6245. GL_CHECK(glDrawArraysInstanced(prim.m_type
  6246. , 0
  6247. , numVertices
  6248. , draw.m_numInstances
  6249. ) );
  6250. }
  6251. }
  6252. if (hasOcclusionQuery)
  6253. {
  6254. m_occlusionQuery.end();
  6255. }
  6256. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  6257. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  6258. statsNumInstances[primIndex] += numInstances;
  6259. statsNumIndices += numIndices;
  6260. }
  6261. }
  6262. }
  6263. blitMsaaFbo();
  6264. if (m_vaoSupport)
  6265. {
  6266. GL_CHECK(glBindVertexArray(m_vao) );
  6267. }
  6268. if (0 < _render->m_num)
  6269. {
  6270. if (0 != (m_resolution.m_flags & BGFX_RESET_FLUSH_AFTER_RENDER) )
  6271. {
  6272. GL_CHECK(glFlush() );
  6273. }
  6274. captureElapsed = -bx::getHPCounter();
  6275. capture();
  6276. captureElapsed += bx::getHPCounter();
  6277. BGFX_GPU_PROFILER_END();
  6278. BGFX_PROFILER_END();
  6279. }
  6280. }
  6281. BGFX_GPU_PROFILER_END();
  6282. m_glctx.makeCurrent(NULL);
  6283. int64_t now = bx::getHPCounter();
  6284. elapsed += now;
  6285. static int64_t last = now;
  6286. Stats& perfStats = _render->m_perfStats;
  6287. perfStats.cpuTimeBegin = last;
  6288. int64_t frameTime = now - last;
  6289. last = now;
  6290. static int64_t min = frameTime;
  6291. static int64_t max = frameTime;
  6292. min = min > frameTime ? frameTime : min;
  6293. max = max < frameTime ? frameTime : max;
  6294. static uint32_t maxGpuLatency = 0;
  6295. static double maxGpuElapsed = 0.0f;
  6296. double elapsedGpuMs = 0.0;
  6297. uint64_t elapsedGl = 0;
  6298. if (m_timerQuerySupport)
  6299. {
  6300. m_gpuTimer.end();
  6301. do
  6302. {
  6303. elapsedGl = m_gpuTimer.m_elapsed;
  6304. elapsedGpuMs = double(elapsedGl)/1e6;
  6305. maxGpuElapsed = elapsedGpuMs > maxGpuElapsed ? elapsedGpuMs : maxGpuElapsed;
  6306. }
  6307. while (m_gpuTimer.get() );
  6308. maxGpuLatency = bx::uint32_imax(maxGpuLatency, m_gpuTimer.m_control.available()-1);
  6309. }
  6310. const int64_t timerFreq = bx::getHPFrequency();
  6311. perfStats.cpuTimeEnd = now;
  6312. perfStats.cpuTimerFreq = timerFreq;
  6313. perfStats.gpuTimeBegin = m_gpuTimer.m_begin;
  6314. perfStats.gpuTimeEnd = m_gpuTimer.m_end;
  6315. perfStats.gpuTimerFreq = 1000000000;
  6316. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  6317. {
  6318. TextVideoMem& tvm = m_textVideoMem;
  6319. static int64_t next = now;
  6320. if (now >= next)
  6321. {
  6322. next = now + timerFreq;
  6323. double freq = double(timerFreq);
  6324. double toMs = 1000.0/freq;
  6325. tvm.clear();
  6326. uint16_t pos = 0;
  6327. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  6328. , getRendererName()
  6329. );
  6330. tvm.printf(0, pos++, 0x8f, " Vendor: %s ", m_vendor);
  6331. tvm.printf(0, pos++, 0x8f, " Renderer: %s ", m_renderer);
  6332. tvm.printf(0, pos++, 0x8f, " Version: %s ", m_version);
  6333. tvm.printf(0, pos++, 0x8f, " GLSL version: %s ", m_glslVersion);
  6334. char processMemoryUsed[16];
  6335. bx::prettify(processMemoryUsed, BX_COUNTOF(processMemoryUsed), bx::getProcessMemoryUsed() );
  6336. tvm.printf(0, pos++, 0x8f, " Memory: %s (process) ", processMemoryUsed);
  6337. pos = 10;
  6338. tvm.printf(10, pos++, 0x8e, " Frame: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  6339. , double(frameTime)*toMs
  6340. , double(min)*toMs
  6341. , double(max)*toMs
  6342. , freq/frameTime
  6343. );
  6344. char hmd[16];
  6345. bx::snprintf(hmd, BX_COUNTOF(hmd), ", [%c] HMD ", hmdEnabled ? '\xfe' : ' ');
  6346. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  6347. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d%s, [%c] MaxAnisotropy "
  6348. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  6349. , 0 != msaa ? '\xfe' : ' '
  6350. , 1<<msaa
  6351. , m_ovr.isInitialized() ? hmd : ", no-HMD "
  6352. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  6353. );
  6354. double elapsedCpuMs = double(elapsed)*toMs;
  6355. tvm.printf(10, pos++, 0x8e, " Submitted: %5d (draw %5d, compute %4d) / CPU %7.4f [ms] %c GPU %7.4f [ms] (latency %d) "
  6356. , _render->m_num
  6357. , statsKeyType[0]
  6358. , statsKeyType[1]
  6359. , elapsedCpuMs
  6360. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  6361. , maxGpuElapsed
  6362. , maxGpuLatency
  6363. );
  6364. maxGpuLatency = 0;
  6365. maxGpuElapsed = 0.0;
  6366. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  6367. {
  6368. tvm.printf(10, pos++, 0x8e, " %10s: %7d (#inst: %5d), submitted: %7d "
  6369. , s_primName[ii]
  6370. , statsNumPrimsRendered[ii]
  6371. , statsNumInstances[ii]
  6372. , statsNumPrimsSubmitted[ii]
  6373. );
  6374. }
  6375. if (NULL != m_renderdocdll)
  6376. {
  6377. tvm.printf(tvm.m_width-27, 0, 0x1f, " [F11 - RenderDoc capture] ");
  6378. }
  6379. tvm.printf(10, pos++, 0x8e, " Indices: %7d ", statsNumIndices);
  6380. tvm.printf(10, pos++, 0x8e, " Uniform size: %7d, Max: %7d ", _render->m_uniformEnd, _render->m_uniformMax);
  6381. tvm.printf(10, pos++, 0x8e, " DVB size: %7d ", _render->m_vboffset);
  6382. tvm.printf(10, pos++, 0x8e, " DIB size: %7d ", _render->m_iboffset);
  6383. pos++;
  6384. tvm.printf(10, pos++, 0x8e, " State cache: ");
  6385. tvm.printf(10, pos++, 0x8e, " VAO | Sampler ");
  6386. tvm.printf(10, pos++, 0x8e, " %6d | %6d "
  6387. , m_vaoStateCache.getCount()
  6388. , m_samplerStateCache.getCount()
  6389. );
  6390. #if BGFX_CONFIG_RENDERER_OPENGL
  6391. if (s_extension[Extension::ATI_meminfo].m_supported)
  6392. {
  6393. GLint vboFree[4];
  6394. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  6395. GLint texFree[4];
  6396. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  6397. GLint rbfFree[4];
  6398. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  6399. pos++;
  6400. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb ");
  6401. char tmp0[16];
  6402. char tmp1[16];
  6403. char tmp2[16];
  6404. char tmp3[16];
  6405. bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]);
  6406. bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]);
  6407. bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]);
  6408. bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]);
  6409. tvm.printf(10, pos++, 0x8e, " VBO: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6410. bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]);
  6411. bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]);
  6412. bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]);
  6413. bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]);
  6414. tvm.printf(10, pos++, 0x8e, " Texture: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6415. bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]);
  6416. bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]);
  6417. bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]);
  6418. bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]);
  6419. tvm.printf(10, pos++, 0x8e, " Render Buffer: %10s, %10s, %10s, %10s ", tmp0, tmp1, tmp2, tmp3);
  6420. }
  6421. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  6422. {
  6423. GLint dedicated;
  6424. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  6425. GLint totalAvail;
  6426. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  6427. GLint currAvail;
  6428. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  6429. GLint evictedCount;
  6430. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  6431. GLint evictedMemory;
  6432. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  6433. pos++;
  6434. char tmp0[16];
  6435. char tmp1[16];
  6436. bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated);
  6437. tvm.printf(10, pos++, 0x8e, " Dedicated: %10s ", tmp0);
  6438. bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail);
  6439. bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail);
  6440. tvm.printf(10, pos++, 0x8e, " Available: %10s / %10s ", tmp0, tmp1);
  6441. bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount);
  6442. bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory);
  6443. tvm.printf(10, pos++, 0x8e, " Eviction: %10s / %10s ", tmp0, tmp1);
  6444. }
  6445. #endif // BGFX_CONFIG_RENDERER_OPENGL
  6446. pos++;
  6447. double captureMs = double(captureElapsed)*toMs;
  6448. tvm.printf(10, pos++, 0x8e, " Capture: %7.4f [ms] ", captureMs);
  6449. uint8_t attr[2] = { 0x89, 0x8a };
  6450. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  6451. tvm.printf(10, pos++, attr[attrIndex&1], " Submit wait: %7.4f [ms] ", double(_render->m_waitSubmit)*toMs);
  6452. tvm.printf(10, pos++, attr[(attrIndex+1)&1], " Render wait: %7.4f [ms] ", double(_render->m_waitRender)*toMs);
  6453. min = frameTime;
  6454. max = frameTime;
  6455. }
  6456. blit(this, _textVideoMemBlitter, tvm);
  6457. }
  6458. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  6459. {
  6460. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  6461. }
  6462. GL_CHECK(glFrameTerminatorGREMEDY() );
  6463. }
  6464. } } // namespace bgfx
  6465. #undef BGFX_GPU_PROFILER_BIND
  6466. #undef BGFX_GPU_PROFILER_UNBIND
  6467. #undef BGFX_GPU_PROFILER_BEGIN
  6468. #undef BGFX_GPU_PROFILER_BEGIN_DYNAMIC
  6469. #undef BGFX_GPU_PROFILER_END
  6470. #else
  6471. namespace bgfx { namespace gl
  6472. {
  6473. RendererContextI* rendererCreate()
  6474. {
  6475. return NULL;
  6476. }
  6477. void rendererDestroy()
  6478. {
  6479. }
  6480. } /* namespace gl */ } // namespace bgfx
  6481. #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)