renderer_gl.cpp 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997
  1. /*
  2. * Copyright 2011-2015 Branimir Karadzic. All rights reserved.
  3. * License: http://www.opensource.org/licenses/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. namespace bgfx { namespace gl
  11. {
  12. static char s_viewName[BGFX_CONFIG_MAX_VIEWS][BGFX_CONFIG_MAX_VIEW_NAME];
  13. struct PrimInfo
  14. {
  15. GLenum m_type;
  16. uint32_t m_min;
  17. uint32_t m_div;
  18. uint32_t m_sub;
  19. };
  20. static const PrimInfo s_primInfo[] =
  21. {
  22. { GL_TRIANGLES, 3, 3, 0 },
  23. { GL_TRIANGLE_STRIP, 3, 1, 2 },
  24. { GL_LINES, 2, 2, 0 },
  25. { GL_LINE_STRIP, 2, 1, 1 },
  26. { GL_POINTS, 1, 1, 0 },
  27. };
  28. static const char* s_primName[] =
  29. {
  30. "TriList",
  31. "TriStrip",
  32. "Line",
  33. "LineStrip",
  34. "Point",
  35. };
  36. static const char* s_attribName[] =
  37. {
  38. "a_position",
  39. "a_normal",
  40. "a_tangent",
  41. "a_bitangent",
  42. "a_color0",
  43. "a_color1",
  44. "a_indices",
  45. "a_weight",
  46. "a_texcoord0",
  47. "a_texcoord1",
  48. "a_texcoord2",
  49. "a_texcoord3",
  50. "a_texcoord4",
  51. "a_texcoord5",
  52. "a_texcoord6",
  53. "a_texcoord7",
  54. };
  55. BX_STATIC_ASSERT(Attrib::Count == BX_COUNTOF(s_attribName) );
  56. static const char* s_instanceDataName[] =
  57. {
  58. "i_data0",
  59. "i_data1",
  60. "i_data2",
  61. "i_data3",
  62. "i_data4",
  63. };
  64. BX_STATIC_ASSERT(BGFX_CONFIG_MAX_INSTANCE_DATA_COUNT == BX_COUNTOF(s_instanceDataName) );
  65. static const GLenum s_access[] =
  66. {
  67. GL_READ_ONLY,
  68. GL_WRITE_ONLY,
  69. GL_READ_WRITE,
  70. };
  71. BX_STATIC_ASSERT(Access::Count == BX_COUNTOF(s_access) );
  72. static const GLenum s_attribType[] =
  73. {
  74. GL_UNSIGNED_BYTE,
  75. GL_SHORT,
  76. GL_HALF_FLOAT,
  77. GL_FLOAT,
  78. };
  79. BX_STATIC_ASSERT(AttribType::Count == BX_COUNTOF(s_attribType) );
  80. struct Blend
  81. {
  82. GLenum m_src;
  83. GLenum m_dst;
  84. bool m_factor;
  85. };
  86. static const Blend s_blendFactor[] =
  87. {
  88. { 0, 0, false }, // ignored
  89. { GL_ZERO, GL_ZERO, false }, // ZERO
  90. { GL_ONE, GL_ONE, false }, // ONE
  91. { GL_SRC_COLOR, GL_SRC_COLOR, false }, // SRC_COLOR
  92. { GL_ONE_MINUS_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, false }, // INV_SRC_COLOR
  93. { GL_SRC_ALPHA, GL_SRC_ALPHA, false }, // SRC_ALPHA
  94. { GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, false }, // INV_SRC_ALPHA
  95. { GL_DST_ALPHA, GL_DST_ALPHA, false }, // DST_ALPHA
  96. { GL_ONE_MINUS_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, false }, // INV_DST_ALPHA
  97. { GL_DST_COLOR, GL_DST_COLOR, false }, // DST_COLOR
  98. { GL_ONE_MINUS_DST_COLOR, GL_ONE_MINUS_DST_COLOR, false }, // INV_DST_COLOR
  99. { GL_SRC_ALPHA_SATURATE, GL_ONE, false }, // SRC_ALPHA_SAT
  100. { GL_CONSTANT_COLOR, GL_CONSTANT_COLOR, true }, // FACTOR
  101. { GL_ONE_MINUS_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, true }, // INV_FACTOR
  102. };
  103. static const GLenum s_blendEquation[] =
  104. {
  105. GL_FUNC_ADD,
  106. GL_FUNC_SUBTRACT,
  107. GL_FUNC_REVERSE_SUBTRACT,
  108. GL_MIN,
  109. GL_MAX,
  110. };
  111. static const GLenum s_cmpFunc[] =
  112. {
  113. 0, // ignored
  114. GL_LESS,
  115. GL_LEQUAL,
  116. GL_EQUAL,
  117. GL_GEQUAL,
  118. GL_GREATER,
  119. GL_NOTEQUAL,
  120. GL_NEVER,
  121. GL_ALWAYS,
  122. };
  123. static const GLenum s_stencilOp[] =
  124. {
  125. GL_ZERO,
  126. GL_KEEP,
  127. GL_REPLACE,
  128. GL_INCR_WRAP,
  129. GL_INCR,
  130. GL_DECR_WRAP,
  131. GL_DECR,
  132. GL_INVERT,
  133. };
  134. static const GLenum s_stencilFace[] =
  135. {
  136. GL_FRONT_AND_BACK,
  137. GL_FRONT,
  138. GL_BACK,
  139. };
  140. static const GLenum s_textureAddress[] =
  141. {
  142. GL_REPEAT,
  143. GL_MIRRORED_REPEAT,
  144. GL_CLAMP_TO_EDGE,
  145. };
  146. static const GLenum s_textureFilterMag[] =
  147. {
  148. GL_LINEAR,
  149. GL_NEAREST,
  150. GL_LINEAR,
  151. };
  152. static const GLenum s_textureFilterMin[][3] =
  153. {
  154. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  155. { GL_NEAREST, GL_LINEAR_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_NEAREST },
  156. { GL_LINEAR, GL_LINEAR_MIPMAP_LINEAR, GL_NEAREST_MIPMAP_LINEAR },
  157. };
  158. struct TextureFormatInfo
  159. {
  160. GLenum m_internalFmt;
  161. GLenum m_internalFmtSrgb;
  162. GLenum m_fmt;
  163. GLenum m_type;
  164. bool m_supported;
  165. };
  166. static TextureFormatInfo s_textureFormat[] =
  167. {
  168. { GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_ZERO, false }, // BC1
  169. { GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_ZERO, false }, // BC2
  170. { GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_ZERO, false }, // BC3
  171. { GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_ZERO, false }, // BC4
  172. { GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_ZERO, false }, // BC5
  173. { GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_ZERO, false }, // BC6H
  174. { GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_ZERO, false }, // BC7
  175. { GL_ETC1_RGB8_OES, GL_ZERO, GL_ETC1_RGB8_OES, GL_ZERO, false }, // ETC1
  176. { GL_COMPRESSED_RGB8_ETC2, GL_ZERO, GL_COMPRESSED_RGB8_ETC2, GL_ZERO, false }, // ETC2
  177. { GL_COMPRESSED_RGBA8_ETC2_EAC, GL_COMPRESSED_SRGB8_ETC2, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_ZERO, false }, // ETC2A
  178. { GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_ZERO, false }, // ETC2A1
  179. { GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12
  180. { GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14
  181. { GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG, GL_ZERO, false }, // PTC12A
  182. { GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, GL_ZERO, false }, // PTC14A
  183. { GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG, GL_ZERO, false }, // PTC22
  184. { GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG, GL_ZERO, false }, // PTC24
  185. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // Unknown
  186. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // R1
  187. { GL_R8, GL_ZERO, GL_RED, GL_UNSIGNED_BYTE, false }, // R8
  188. { GL_R16, GL_ZERO, GL_RED, GL_UNSIGNED_SHORT, false }, // R16
  189. { GL_R16F, GL_ZERO, GL_RED, GL_HALF_FLOAT, false }, // R16F
  190. { GL_R32UI, GL_ZERO, GL_RED, GL_UNSIGNED_INT, false }, // R32
  191. { GL_R32F, GL_ZERO, GL_RED, GL_FLOAT, false }, // R32F
  192. { GL_RG8, GL_ZERO, GL_RG, GL_UNSIGNED_BYTE, false }, // RG8
  193. { GL_RG16, GL_ZERO, GL_RG, GL_UNSIGNED_SHORT, false }, // RG16
  194. { GL_RG16F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG16F
  195. { GL_RG32UI, GL_ZERO, GL_RG, GL_UNSIGNED_INT, false }, // RG32
  196. { GL_RG32F, GL_ZERO, GL_RG, GL_FLOAT, false }, // RG32F
  197. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_BGRA, GL_UNSIGNED_BYTE, false }, // BGRA8
  198. { GL_RGBA8, GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA8
  199. { GL_RGBA16, GL_ZERO, GL_RGBA, GL_UNSIGNED_BYTE, false }, // RGBA16
  200. { GL_RGBA16F, GL_ZERO, GL_RGBA, GL_HALF_FLOAT, false }, // RGBA16F
  201. { GL_RGBA32UI, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT, false }, // RGBA32
  202. { GL_RGBA32F, GL_ZERO, GL_RGBA, GL_FLOAT, false }, // RGBA32F
  203. { GL_RGB565, GL_ZERO, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, false }, // R5G6B5
  204. { GL_RGBA4, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, false }, // RGBA4
  205. { GL_RGB5_A1, GL_ZERO, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, false }, // RGB5A1
  206. { GL_RGB10_A2, GL_ZERO, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, false }, // RGB10A2
  207. { GL_R11F_G11F_B10F, GL_ZERO, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, false }, // R11G11B10F
  208. { GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO, false }, // UnknownDepth
  209. { GL_DEPTH_COMPONENT16, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, false }, // D16
  210. { GL_DEPTH_COMPONENT24, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D24
  211. { GL_DEPTH24_STENCIL8, GL_ZERO, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, false }, // D24S8
  212. { GL_DEPTH_COMPONENT32, GL_ZERO, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, false }, // D32
  213. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D16F
  214. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D24F
  215. { GL_DEPTH_COMPONENT32F, GL_ZERO, GL_DEPTH_COMPONENT, GL_FLOAT, false }, // D32F
  216. { GL_STENCIL_INDEX8, GL_ZERO, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, false }, // D0S8
  217. };
  218. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_textureFormat) );
  219. static bool s_textureFilter[TextureFormat::Count+1];
  220. static GLenum s_rboFormat[] =
  221. {
  222. GL_ZERO, // BC1
  223. GL_ZERO, // BC2
  224. GL_ZERO, // BC3
  225. GL_ZERO, // BC4
  226. GL_ZERO, // BC5
  227. GL_ZERO, // BC6H
  228. GL_ZERO, // BC7
  229. GL_ZERO, // ETC1
  230. GL_ZERO, // ETC2
  231. GL_ZERO, // ETC2A
  232. GL_ZERO, // ETC2A1
  233. GL_ZERO, // PTC12
  234. GL_ZERO, // PTC14
  235. GL_ZERO, // PTC12A
  236. GL_ZERO, // PTC14A
  237. GL_ZERO, // PTC22
  238. GL_ZERO, // PTC24
  239. GL_ZERO, // Unknown
  240. GL_ZERO, // R1
  241. GL_R8, // R8
  242. GL_R16, // R16
  243. GL_R16F, // R16F
  244. GL_R32UI, // R32
  245. GL_R32F, // R32F
  246. GL_RG8, // RG8
  247. GL_RG16, // RG16
  248. GL_RG16F, // RG16F
  249. GL_RG32UI, // RG32
  250. GL_RG32F, // RG32F
  251. GL_RGBA8, // BGRA8
  252. GL_RGBA8, // RGBA8
  253. GL_RGBA16, // RGBA16
  254. GL_RGBA16F, // RGBA16F
  255. GL_RGBA32UI, // RGBA32
  256. GL_RGBA32F, // RGBA32F
  257. GL_RGB565, // R5G6B5
  258. GL_RGBA4, // RGBA4
  259. GL_RGB5_A1, // RGB5A1
  260. GL_RGB10_A2, // RGB10A2
  261. GL_R11F_G11F_B10F, // R11G11B10F
  262. GL_ZERO, // UnknownDepth
  263. GL_DEPTH_COMPONENT16, // D16
  264. GL_DEPTH_COMPONENT24, // D24
  265. GL_DEPTH24_STENCIL8, // D24S8
  266. GL_DEPTH_COMPONENT32, // D32
  267. GL_DEPTH_COMPONENT32F, // D16F
  268. GL_DEPTH_COMPONENT32F, // D24F
  269. GL_DEPTH_COMPONENT32F, // D32F
  270. GL_STENCIL_INDEX8, // D0S8
  271. };
  272. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_rboFormat) );
  273. static GLenum s_imageFormat[] =
  274. {
  275. GL_ZERO, // BC1
  276. GL_ZERO, // BC2
  277. GL_ZERO, // BC3
  278. GL_ZERO, // BC4
  279. GL_ZERO, // BC5
  280. GL_ZERO, // BC6H
  281. GL_ZERO, // BC7
  282. GL_ZERO, // ETC1
  283. GL_ZERO, // ETC2
  284. GL_ZERO, // ETC2A
  285. GL_ZERO, // ETC2A1
  286. GL_ZERO, // PTC12
  287. GL_ZERO, // PTC14
  288. GL_ZERO, // PTC12A
  289. GL_ZERO, // PTC14A
  290. GL_ZERO, // PTC22
  291. GL_ZERO, // PTC24
  292. GL_ZERO, // Unknown
  293. GL_ZERO, // R1
  294. GL_R8, // R8
  295. GL_R16, // R16
  296. GL_R16F, // R16F
  297. GL_R32UI, // R32
  298. GL_R32F, // R32F
  299. GL_RG8, // RG8
  300. GL_RG16, // RG16
  301. GL_RG16F, // RG16F
  302. GL_RG32UI, // RG32
  303. GL_RG32F, // RG32F
  304. GL_RGBA8, // BGRA8
  305. GL_RGBA8, // RGBA8
  306. GL_RGBA16, // RGBA16
  307. GL_RGBA16F, // RGBA16F
  308. GL_RGBA32UI, // RGBA32
  309. GL_RGBA32F, // RGBA32F
  310. GL_RGB565, // R5G6B5
  311. GL_RGBA4, // RGBA4
  312. GL_RGB5_A1, // RGB5A1
  313. GL_RGB10_A2, // RGB10A2
  314. GL_R11F_G11F_B10F, // R11G11B10F
  315. GL_ZERO, // UnknownDepth
  316. GL_ZERO, // D16
  317. GL_ZERO, // D24
  318. GL_ZERO, // D24S8
  319. GL_ZERO, // D32
  320. GL_ZERO, // D16F
  321. GL_ZERO, // D24F
  322. GL_ZERO, // D32F
  323. GL_ZERO, // D0S8
  324. };
  325. BX_STATIC_ASSERT(TextureFormat::Count == BX_COUNTOF(s_imageFormat) );
  326. struct Extension
  327. {
  328. enum Enum
  329. {
  330. AMD_conservative_depth,
  331. AMD_multi_draw_indirect,
  332. ANGLE_depth_texture,
  333. ANGLE_framebuffer_blit,
  334. ANGLE_framebuffer_multisample,
  335. ANGLE_instanced_arrays,
  336. ANGLE_texture_compression_dxt1,
  337. ANGLE_texture_compression_dxt3,
  338. ANGLE_texture_compression_dxt5,
  339. ANGLE_timer_query,
  340. ANGLE_translated_shader_source,
  341. APPLE_texture_format_BGRA8888,
  342. APPLE_texture_max_level,
  343. ARB_compute_shader,
  344. ARB_conservative_depth,
  345. ARB_debug_label,
  346. ARB_debug_output,
  347. ARB_depth_buffer_float,
  348. ARB_depth_clamp,
  349. ARB_draw_buffers_blend,
  350. ARB_draw_indirect,
  351. ARB_draw_instanced,
  352. ARB_ES3_compatibility,
  353. ARB_framebuffer_object,
  354. ARB_framebuffer_sRGB,
  355. ARB_get_program_binary,
  356. ARB_half_float_pixel,
  357. ARB_half_float_vertex,
  358. ARB_instanced_arrays,
  359. ARB_invalidate_subdata,
  360. ARB_map_buffer_range,
  361. ARB_multi_draw_indirect,
  362. ARB_multisample,
  363. ARB_occlusion_query,
  364. ARB_occlusion_query2,
  365. ARB_program_interface_query,
  366. ARB_sampler_objects,
  367. ARB_seamless_cube_map,
  368. ARB_shader_bit_encoding,
  369. ARB_shader_image_load_store,
  370. ARB_shader_storage_buffer_object,
  371. ARB_shader_texture_lod,
  372. ARB_texture_compression_bptc,
  373. ARB_texture_compression_rgtc,
  374. ARB_texture_float,
  375. ARB_texture_multisample,
  376. ARB_texture_rg,
  377. ARB_texture_rgb10_a2ui,
  378. ARB_texture_stencil8,
  379. ARB_texture_storage,
  380. ARB_texture_swizzle,
  381. ARB_timer_query,
  382. ARB_uniform_buffer_object,
  383. ARB_vertex_array_object,
  384. ARB_vertex_type_2_10_10_10_rev,
  385. ATI_meminfo,
  386. CHROMIUM_color_buffer_float_rgb,
  387. CHROMIUM_color_buffer_float_rgba,
  388. CHROMIUM_depth_texture,
  389. CHROMIUM_framebuffer_multisample,
  390. CHROMIUM_texture_compression_dxt3,
  391. CHROMIUM_texture_compression_dxt5,
  392. EXT_bgra,
  393. EXT_blend_color,
  394. EXT_blend_minmax,
  395. EXT_blend_subtract,
  396. EXT_color_buffer_half_float,
  397. EXT_color_buffer_float,
  398. EXT_compressed_ETC1_RGB8_sub_texture,
  399. EXT_debug_label,
  400. EXT_debug_marker,
  401. EXT_debug_tool,
  402. EXT_discard_framebuffer,
  403. EXT_disjoint_timer_query,
  404. EXT_draw_buffers,
  405. EXT_frag_depth,
  406. EXT_framebuffer_blit,
  407. EXT_framebuffer_object,
  408. EXT_framebuffer_sRGB,
  409. EXT_multi_draw_indirect,
  410. EXT_occlusion_query_boolean,
  411. EXT_packed_float,
  412. EXT_read_format_bgra,
  413. EXT_shader_image_load_store,
  414. EXT_shader_texture_lod,
  415. EXT_shadow_samplers,
  416. EXT_texture_array,
  417. EXT_texture_compression_dxt1,
  418. EXT_texture_compression_latc,
  419. EXT_texture_compression_rgtc,
  420. EXT_texture_compression_s3tc,
  421. EXT_texture_filter_anisotropic,
  422. EXT_texture_format_BGRA8888,
  423. EXT_texture_rg,
  424. EXT_texture_sRGB,
  425. EXT_texture_storage,
  426. EXT_texture_swizzle,
  427. EXT_texture_type_2_10_10_10_REV,
  428. EXT_timer_query,
  429. EXT_unpack_subimage,
  430. GOOGLE_depth_texture,
  431. GREMEDY_string_marker,
  432. GREMEDY_frame_terminator,
  433. IMG_multisampled_render_to_texture,
  434. IMG_read_format,
  435. IMG_shader_binary,
  436. IMG_texture_compression_pvrtc,
  437. IMG_texture_compression_pvrtc2,
  438. IMG_texture_format_BGRA8888,
  439. INTEL_fragment_shader_ordering,
  440. KHR_debug,
  441. KHR_no_error,
  442. MOZ_WEBGL_compressed_texture_s3tc,
  443. MOZ_WEBGL_depth_texture,
  444. NV_draw_buffers,
  445. NVX_gpu_memory_info,
  446. OES_compressed_ETC1_RGB8_texture,
  447. OES_depth24,
  448. OES_depth32,
  449. OES_depth_texture,
  450. OES_element_index_uint,
  451. OES_fragment_precision_high,
  452. OES_get_program_binary,
  453. OES_required_internalformat,
  454. OES_packed_depth_stencil,
  455. OES_read_format,
  456. OES_rgb8_rgba8,
  457. OES_standard_derivatives,
  458. OES_texture_3D,
  459. OES_texture_float,
  460. OES_texture_float_linear,
  461. OES_texture_npot,
  462. OES_texture_half_float,
  463. OES_texture_half_float_linear,
  464. OES_texture_stencil8,
  465. OES_vertex_array_object,
  466. OES_vertex_half_float,
  467. OES_vertex_type_10_10_10_2,
  468. WEBGL_color_buffer_float,
  469. WEBGL_compressed_texture_etc1,
  470. WEBGL_compressed_texture_s3tc,
  471. WEBGL_compressed_texture_pvrtc,
  472. WEBGL_depth_texture,
  473. WEBGL_draw_buffers,
  474. WEBKIT_EXT_texture_filter_anisotropic,
  475. WEBKIT_WEBGL_compressed_texture_s3tc,
  476. WEBKIT_WEBGL_depth_texture,
  477. Count
  478. };
  479. const char* m_name;
  480. bool m_supported;
  481. bool m_initialize;
  482. };
  483. // Extension registry
  484. //
  485. // ANGLE:
  486. // https://github.com/google/angle/tree/master/extensions
  487. //
  488. // CHROMIUM:
  489. // https://chromium.googlesource.com/chromium/src.git/+/refs/heads/git-svn/gpu/GLES2/extensions/CHROMIUM
  490. //
  491. // EGL:
  492. // https://www.khronos.org/registry/egl/extensions/
  493. //
  494. // GL:
  495. // https://www.opengl.org/registry/
  496. //
  497. // GLES:
  498. // https://www.khronos.org/registry/gles/extensions/
  499. //
  500. // WEBGL:
  501. // https://www.khronos.org/registry/webgl/extensions/
  502. //
  503. static Extension s_extension[] =
  504. {
  505. { "AMD_conservative_depth", false, true },
  506. { "AMD_multi_draw_indirect", false, true },
  507. { "ANGLE_depth_texture", false, true },
  508. { "ANGLE_framebuffer_blit", false, true },
  509. { "ANGLE_framebuffer_multisample", false, false },
  510. { "ANGLE_instanced_arrays", false, true },
  511. { "ANGLE_texture_compression_dxt1", false, true },
  512. { "ANGLE_texture_compression_dxt3", false, true },
  513. { "ANGLE_texture_compression_dxt5", false, true },
  514. { "ANGLE_timer_query", false, true },
  515. { "ANGLE_translated_shader_source", false, true },
  516. { "APPLE_texture_format_BGRA8888", false, true },
  517. { "APPLE_texture_max_level", false, true },
  518. { "ARB_compute_shader", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  519. { "ARB_conservative_depth", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  520. { "ARB_debug_label", false, true },
  521. { "ARB_debug_output", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  522. { "ARB_depth_buffer_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  523. { "ARB_depth_clamp", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  524. { "ARB_draw_buffers_blend", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  525. { "ARB_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 40, true },
  526. { "ARB_draw_instanced", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  527. { "ARB_ES3_compatibility", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  528. { "ARB_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  529. { "ARB_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  530. { "ARB_get_program_binary", BGFX_CONFIG_RENDERER_OPENGL >= 41, true },
  531. { "ARB_half_float_pixel", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  532. { "ARB_half_float_vertex", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  533. { "ARB_instanced_arrays", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  534. { "ARB_invalidate_subdata", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  535. { "ARB_map_buffer_range", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  536. { "ARB_multi_draw_indirect", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  537. { "ARB_multisample", false, true },
  538. { "ARB_occlusion_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  539. { "ARB_occlusion_query2", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  540. { "ARB_program_interface_query", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  541. { "ARB_sampler_objects", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  542. { "ARB_seamless_cube_map", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  543. { "ARB_shader_bit_encoding", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  544. { "ARB_shader_image_load_store", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  545. { "ARB_shader_storage_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  546. { "ARB_shader_texture_lod", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  547. { "ARB_texture_compression_bptc", BGFX_CONFIG_RENDERER_OPENGL >= 44, true },
  548. { "ARB_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  549. { "ARB_texture_float", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  550. { "ARB_texture_multisample", BGFX_CONFIG_RENDERER_OPENGL >= 32, true },
  551. { "ARB_texture_rg", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  552. { "ARB_texture_rgb10_a2ui", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  553. { "ARB_texture_stencil8", false, true },
  554. { "ARB_texture_storage", BGFX_CONFIG_RENDERER_OPENGL >= 42, true },
  555. { "ARB_texture_swizzle", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  556. { "ARB_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  557. { "ARB_uniform_buffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  558. { "ARB_vertex_array_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  559. { "ARB_vertex_type_2_10_10_10_rev", false, true },
  560. { "ATI_meminfo", false, true },
  561. { "CHROMIUM_color_buffer_float_rgb", false, true },
  562. { "CHROMIUM_color_buffer_float_rgba", false, true },
  563. { "CHROMIUM_depth_texture", false, true },
  564. { "CHROMIUM_framebuffer_multisample", false, true },
  565. { "CHROMIUM_texture_compression_dxt3", false, true },
  566. { "CHROMIUM_texture_compression_dxt5", false, true },
  567. { "EXT_bgra", false, true },
  568. { "EXT_blend_color", BGFX_CONFIG_RENDERER_OPENGL >= 31, true },
  569. { "EXT_blend_minmax", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  570. { "EXT_blend_subtract", BGFX_CONFIG_RENDERER_OPENGL >= 14, true },
  571. { "EXT_color_buffer_half_float", false, true }, // GLES2 extension.
  572. { "EXT_color_buffer_float", false, true }, // GLES2 extension.
  573. { "EXT_compressed_ETC1_RGB8_sub_texture", false, true }, // GLES2 extension.
  574. { "EXT_debug_label", false, true },
  575. { "EXT_debug_marker", false, true },
  576. { "EXT_debug_tool", false, true }, // RenderDoc extension.
  577. { "EXT_discard_framebuffer", false, true }, // GLES2 extension.
  578. { "EXT_disjoint_timer_query", false, true }, // GLES2 extension.
  579. { "EXT_draw_buffers", false, true }, // GLES2 extension.
  580. { "EXT_frag_depth", false, true }, // GLES2 extension.
  581. { "EXT_framebuffer_blit", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  582. { "EXT_framebuffer_object", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  583. { "EXT_framebuffer_sRGB", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  584. { "EXT_multi_draw_indirect", false, true }, // GLES3.1 extension.
  585. { "EXT_occlusion_query_boolean", false, true },
  586. { "EXT_packed_float", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  587. { "EXT_read_format_bgra", false, true },
  588. { "EXT_shader_image_load_store", false, true },
  589. { "EXT_shader_texture_lod", false, true }, // GLES2 extension.
  590. { "EXT_shadow_samplers", false, true },
  591. { "EXT_texture_array", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  592. { "EXT_texture_compression_dxt1", false, true },
  593. { "EXT_texture_compression_latc", false, true },
  594. { "EXT_texture_compression_rgtc", BGFX_CONFIG_RENDERER_OPENGL >= 30, true },
  595. { "EXT_texture_compression_s3tc", false, true },
  596. { "EXT_texture_filter_anisotropic", false, true },
  597. { "EXT_texture_format_BGRA8888", false, true },
  598. { "EXT_texture_rg", false, true }, // GLES2 extension.
  599. { "EXT_texture_sRGB", false, true },
  600. { "EXT_texture_storage", false, true },
  601. { "EXT_texture_swizzle", false, true },
  602. { "EXT_texture_type_2_10_10_10_REV", false, true },
  603. { "EXT_timer_query", BGFX_CONFIG_RENDERER_OPENGL >= 33, true },
  604. { "EXT_unpack_subimage", false, true },
  605. { "GOOGLE_depth_texture", false, true },
  606. { "GREMEDY_string_marker", false, true },
  607. { "GREMEDY_frame_terminator", false, true },
  608. { "IMG_multisampled_render_to_texture", false, true },
  609. { "IMG_read_format", false, true },
  610. { "IMG_shader_binary", false, true },
  611. { "IMG_texture_compression_pvrtc", false, true },
  612. { "IMG_texture_compression_pvrtc2", false, true },
  613. { "IMG_texture_format_BGRA8888", false, true },
  614. { "INTEL_fragment_shader_ordering", false, true },
  615. { "KHR_debug", BGFX_CONFIG_RENDERER_OPENGL >= 43, true },
  616. { "KHR_no_error", false, true },
  617. { "MOZ_WEBGL_compressed_texture_s3tc", false, true },
  618. { "MOZ_WEBGL_depth_texture", false, true },
  619. { "NV_draw_buffers", false, true }, // GLES2 extension.
  620. { "NVX_gpu_memory_info", false, true },
  621. { "OES_compressed_ETC1_RGB8_texture", false, true },
  622. { "OES_depth24", false, true },
  623. { "OES_depth32", false, true },
  624. { "OES_depth_texture", false, true },
  625. { "OES_element_index_uint", false, true },
  626. { "OES_fragment_precision_high", false, true },
  627. { "OES_get_program_binary", false, true },
  628. { "OES_required_internalformat", false, true },
  629. { "OES_packed_depth_stencil", false, true },
  630. { "OES_read_format", false, true },
  631. { "OES_rgb8_rgba8", false, true },
  632. { "OES_standard_derivatives", false, true },
  633. { "OES_texture_3D", false, true },
  634. { "OES_texture_float", false, true },
  635. { "OES_texture_float_linear", false, true },
  636. { "OES_texture_npot", false, true },
  637. { "OES_texture_half_float", false, true },
  638. { "OES_texture_half_float_linear", false, true },
  639. { "OES_texture_stencil8", false, true },
  640. { "OES_vertex_array_object", false, !BX_PLATFORM_IOS },
  641. { "OES_vertex_half_float", false, true },
  642. { "OES_vertex_type_10_10_10_2", false, true },
  643. { "WEBGL_color_buffer_float", false, true },
  644. { "WEBGL_compressed_texture_etc1", false, true },
  645. { "WEBGL_compressed_texture_s3tc", false, true },
  646. { "WEBGL_compressed_texture_pvrtc", false, true },
  647. { "WEBGL_depth_texture", false, true },
  648. { "WEBGL_draw_buffers", false, true },
  649. { "WEBKIT_EXT_texture_filter_anisotropic", false, true },
  650. { "WEBKIT_WEBGL_compressed_texture_s3tc", false, true },
  651. { "WEBKIT_WEBGL_depth_texture", false, true },
  652. };
  653. BX_STATIC_ASSERT(Extension::Count == BX_COUNTOF(s_extension) );
  654. static const char* s_ARB_shader_texture_lod[] =
  655. {
  656. "texture2DLod",
  657. "texture2DProjLod",
  658. "texture3DLod",
  659. "texture3DProjLod",
  660. "textureCubeLod",
  661. "shadow2DLod",
  662. "shadow2DProjLod",
  663. NULL
  664. // "texture1DLod",
  665. // "texture1DProjLod",
  666. // "shadow1DLod",
  667. // "shadow1DProjLod",
  668. };
  669. static const char* s_EXT_shader_texture_lod[] =
  670. {
  671. "texture2DLod",
  672. "texture2DProjLod",
  673. "textureCubeLod",
  674. NULL
  675. // "texture2DGrad",
  676. // "texture2DProjGrad",
  677. // "textureCubeGrad",
  678. };
  679. static const char* s_EXT_shadow_samplers[] =
  680. {
  681. "shadow2D",
  682. "shadow2DProj",
  683. NULL
  684. };
  685. static const char* s_OES_standard_derivatives[] =
  686. {
  687. "dFdx",
  688. "dFdy",
  689. "fwidth",
  690. NULL
  691. };
  692. static const char* s_OES_texture_3D[] =
  693. {
  694. "texture3D",
  695. "texture3DProj",
  696. "texture3DLod",
  697. "texture3DProjLod",
  698. NULL
  699. };
  700. static const char* s_uisamplers[] =
  701. {
  702. "isampler2D",
  703. "usampler2D",
  704. "isampler3D",
  705. "usampler3D",
  706. "isamplerCube",
  707. "usamplerCube",
  708. NULL
  709. };
  710. static void GL_APIENTRY stubVertexAttribDivisor(GLuint /*_index*/, GLuint /*_divisor*/)
  711. {
  712. }
  713. static void GL_APIENTRY stubDrawArraysInstanced(GLenum _mode, GLint _first, GLsizei _count, GLsizei /*_primcount*/)
  714. {
  715. GL_CHECK(glDrawArrays(_mode, _first, _count) );
  716. }
  717. static void GL_APIENTRY stubDrawElementsInstanced(GLenum _mode, GLsizei _count, GLenum _type, const GLvoid* _indices, GLsizei /*_primcount*/)
  718. {
  719. GL_CHECK(glDrawElements(_mode, _count, _type, _indices) );
  720. }
  721. static void GL_APIENTRY stubFrameTerminatorGREMEDY()
  722. {
  723. }
  724. static void GL_APIENTRY stubInsertEventMarker(GLsizei /*_length*/, const char* /*_marker*/)
  725. {
  726. }
  727. static void GL_APIENTRY stubInsertEventMarkerGREMEDY(GLsizei _length, const char* _marker)
  728. {
  729. // If <marker> is a null-terminated string then <length> should not
  730. // include the terminator.
  731. //
  732. // If <length> is 0 then <marker> is assumed to be null-terminated.
  733. uint32_t size = (0 == _length ? (uint32_t)strlen(_marker) : _length) + 1;
  734. size *= sizeof(wchar_t);
  735. wchar_t* name = (wchar_t*)alloca(size);
  736. mbstowcs(name, _marker, size-2);
  737. GL_CHECK(glStringMarkerGREMEDY(_length, _marker) );
  738. }
  739. static void GL_APIENTRY stubObjectLabel(GLenum /*_identifier*/, GLuint /*_name*/, GLsizei /*_length*/, const char* /*_label*/)
  740. {
  741. }
  742. static void GL_APIENTRY stubInvalidateFramebuffer(GLenum /*_target*/, GLsizei /*_numAttachments*/, const GLenum* /*_attachments*/)
  743. {
  744. }
  745. static void GL_APIENTRY stubMultiDrawArraysIndirect(GLenum _mode, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  746. {
  747. const uint8_t* args = (const uint8_t*)_indirect;
  748. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  749. {
  750. GL_CHECK(glDrawArraysIndirect(_mode, (void*)args) );
  751. args += _stride;
  752. }
  753. }
  754. static void GL_APIENTRY stubMultiDrawElementsIndirect(GLenum _mode, GLenum _type, const void* _indirect, GLsizei _drawcount, GLsizei _stride)
  755. {
  756. const uint8_t* args = (const uint8_t*)_indirect;
  757. for (GLsizei ii = 0; ii < _drawcount; ++ii)
  758. {
  759. GL_CHECK(glDrawElementsIndirect(_mode, _type, (void*)args) );
  760. args += _stride;
  761. }
  762. }
  763. typedef void (*PostSwapBuffersFn)(uint32_t _width, uint32_t _height);
  764. static const char* getGLString(GLenum _name)
  765. {
  766. const char* str = (const char*)glGetString(_name);
  767. glGetError(); // ignore error if glGetString returns NULL.
  768. if (NULL != str)
  769. {
  770. return str;
  771. }
  772. return "<unknown>";
  773. }
  774. static uint32_t getGLStringHash(GLenum _name)
  775. {
  776. const char* str = (const char*)glGetString(_name);
  777. glGetError(); // ignore error if glGetString returns NULL.
  778. if (NULL != str)
  779. {
  780. return bx::hashMurmur2A(str, (uint32_t)strlen(str) );
  781. }
  782. return 0;
  783. }
  784. void dumpExtensions(const char* _extensions)
  785. {
  786. if (NULL != _extensions)
  787. {
  788. char name[1024];
  789. const char* pos = _extensions;
  790. const char* end = _extensions + strlen(_extensions);
  791. while (pos < end)
  792. {
  793. uint32_t len;
  794. const char* space = strchr(pos, ' ');
  795. if (NULL != space)
  796. {
  797. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  798. }
  799. else
  800. {
  801. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  802. }
  803. strncpy(name, pos, len);
  804. name[len] = '\0';
  805. BX_TRACE("\t%s", name);
  806. pos += len+1;
  807. }
  808. }
  809. }
  810. const char* toString(GLenum _enum)
  811. {
  812. switch (_enum)
  813. {
  814. case GL_DEBUG_SOURCE_API: return "API";
  815. case GL_DEBUG_SOURCE_WINDOW_SYSTEM: return "WinSys";
  816. case GL_DEBUG_SOURCE_SHADER_COMPILER: return "Shader";
  817. case GL_DEBUG_SOURCE_THIRD_PARTY: return "3rdparty";
  818. case GL_DEBUG_SOURCE_APPLICATION: return "Application";
  819. case GL_DEBUG_SOURCE_OTHER: return "Other";
  820. case GL_DEBUG_TYPE_ERROR: return "Error";
  821. case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: return "Deprecated behavior";
  822. case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: return "Undefined behavior";
  823. case GL_DEBUG_TYPE_PORTABILITY: return "Portability";
  824. case GL_DEBUG_TYPE_PERFORMANCE: return "Performance";
  825. case GL_DEBUG_TYPE_OTHER: return "Other";
  826. case GL_DEBUG_SEVERITY_HIGH: return "High";
  827. case GL_DEBUG_SEVERITY_MEDIUM: return "Medium";
  828. case GL_DEBUG_SEVERITY_LOW: return "Low";
  829. default:
  830. break;
  831. }
  832. return "<unknown>";
  833. }
  834. void GL_APIENTRY debugProcCb(GLenum _source, GLenum _type, GLuint _id, GLenum _severity, GLsizei /*_length*/, const GLchar* _message, const void* /*_userParam*/)
  835. {
  836. BX_TRACE("src %s, type %s, id %d, severity %s, '%s'"
  837. , toString(_source)
  838. , toString(_type)
  839. , _id
  840. , toString(_severity)
  841. , _message
  842. );
  843. BX_UNUSED(_source, _type, _id, _severity, _message);
  844. }
  845. GLint glGet(GLenum _pname)
  846. {
  847. GLint result = 0;
  848. glGetIntegerv(_pname, &result);
  849. GLenum err = glGetError();
  850. BX_WARN(0 == err, "glGetIntegerv(0x%04x, ...) failed with GL error: 0x%04x.", _pname, err);
  851. return 0 == err ? result : 0;
  852. }
  853. void setTextureFormat(TextureFormat::Enum _format, GLenum _internalFmt, GLenum _fmt, GLenum _type = GL_ZERO)
  854. {
  855. TextureFormatInfo& tfi = s_textureFormat[_format];
  856. tfi.m_internalFmt = _internalFmt;
  857. tfi.m_fmt = _fmt;
  858. tfi.m_type = _type;
  859. }
  860. void initTestTexture(TextureFormat::Enum _format, bool srgb = false)
  861. {
  862. const TextureFormatInfo& tfi = s_textureFormat[_format];
  863. GLenum internalFmt = srgb
  864. ? tfi.m_internalFmtSrgb
  865. : tfi.m_internalFmt
  866. ;
  867. GLsizei size = (16*16*getBitsPerPixel(_format) )/8;
  868. void* data = alloca(size);
  869. if (isCompressed(_format) )
  870. {
  871. glCompressedTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, size, data);
  872. }
  873. else
  874. {
  875. glTexImage2D(GL_TEXTURE_2D, 0, internalFmt, 16, 16, 0, tfi.m_fmt, tfi.m_type, data);
  876. }
  877. }
  878. static bool isTextureFormatValid(TextureFormat::Enum _format, bool srgb = false)
  879. {
  880. const TextureFormatInfo& tfi = s_textureFormat[_format];
  881. GLenum internalFmt = srgb
  882. ? tfi.m_internalFmtSrgb
  883. : tfi.m_internalFmt
  884. ;
  885. if (GL_ZERO == internalFmt)
  886. {
  887. return false;
  888. }
  889. GLuint id;
  890. GL_CHECK(glGenTextures(1, &id) );
  891. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  892. initTestTexture(_format);
  893. GLenum err = glGetError();
  894. BX_WARN(0 == err, "TextureFormat::%s is not supported (%x: %s).", getName(_format), err, glEnumName(err) );
  895. GL_CHECK(glDeleteTextures(1, &id) );
  896. return 0 == err;
  897. }
  898. static bool isImageFormatValid(TextureFormat::Enum _format)
  899. {
  900. if (GL_ZERO == s_imageFormat[_format])
  901. {
  902. return false;
  903. }
  904. GLuint id;
  905. GL_CHECK(glGenTextures(1, &id) );
  906. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  907. GL_CHECK(glTexStorage2D(GL_TEXTURE_2D, 1, s_imageFormat[_format], 16, 16) );
  908. glBindImageTexture(0
  909. , id
  910. , 0
  911. , GL_FALSE
  912. , 0
  913. , GL_READ_WRITE
  914. , s_imageFormat[_format]
  915. );
  916. GLenum err = glGetError();
  917. GL_CHECK(glDeleteTextures(1, &id) );
  918. return 0 == err;
  919. }
  920. static bool isFramebufferFormatValid(TextureFormat::Enum _format, bool srgb = false)
  921. {
  922. const TextureFormatInfo& tfi = s_textureFormat[_format];
  923. GLenum internalFmt = srgb
  924. ? tfi.m_internalFmtSrgb
  925. : tfi.m_internalFmt
  926. ;
  927. if (GL_ZERO == internalFmt
  928. || !tfi.m_supported)
  929. {
  930. return false;
  931. }
  932. GLuint fbo;
  933. GL_CHECK(glGenFramebuffers(1, &fbo) );
  934. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, fbo) );
  935. GLuint id;
  936. GL_CHECK(glGenTextures(1, &id) );
  937. GL_CHECK(glBindTexture(GL_TEXTURE_2D, id) );
  938. initTestTexture(_format);
  939. GLenum err = glGetError();
  940. GLenum attachment;
  941. if (isDepth(_format) )
  942. {
  943. const ImageBlockInfo& info = getBlockInfo(_format);
  944. if (0 < info.stencilBits)
  945. {
  946. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  947. }
  948. else if (0 == info.depthBits)
  949. {
  950. attachment = GL_STENCIL_ATTACHMENT;
  951. }
  952. else
  953. {
  954. attachment = GL_DEPTH_ATTACHMENT;
  955. }
  956. }
  957. else
  958. {
  959. attachment = GL_COLOR_ATTACHMENT0;
  960. }
  961. glFramebufferTexture2D(GL_FRAMEBUFFER
  962. , attachment
  963. , GL_TEXTURE_2D
  964. , id
  965. , 0
  966. );
  967. err = glGetError();
  968. if (0 == err)
  969. {
  970. err = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  971. }
  972. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  973. GL_CHECK(glDeleteFramebuffers(1, &fbo) );
  974. GL_CHECK(glDeleteTextures(1, &id) );
  975. return GL_FRAMEBUFFER_COMPLETE == err;
  976. }
  977. static void getFilters(uint32_t _flags, bool _hasMips, GLenum& _magFilter, GLenum& _minFilter)
  978. {
  979. const uint32_t mag = (_flags&BGFX_TEXTURE_MAG_MASK)>>BGFX_TEXTURE_MAG_SHIFT;
  980. const uint32_t min = (_flags&BGFX_TEXTURE_MIN_MASK)>>BGFX_TEXTURE_MIN_SHIFT;
  981. const uint32_t mip = (_flags&BGFX_TEXTURE_MIP_MASK)>>BGFX_TEXTURE_MIP_SHIFT;
  982. _magFilter = s_textureFilterMag[mag];
  983. _minFilter = s_textureFilterMin[min][_hasMips ? mip+1 : 0];
  984. }
  985. struct RendererContextGL : public RendererContextI
  986. {
  987. RendererContextGL()
  988. : m_numWindows(1)
  989. , m_rtMsaa(false)
  990. , m_fbDiscard(BGFX_CLEAR_NONE)
  991. , m_capture(NULL)
  992. , m_captureSize(0)
  993. , m_maxAnisotropy(0.0f)
  994. , m_maxAnisotropyDefault(0.0f)
  995. , m_maxMsaa(0)
  996. , m_vao(0)
  997. , m_vaoSupport(false)
  998. , m_samplerObjectSupport(false)
  999. , m_shadowSamplersSupport(false)
  1000. , m_programBinarySupport(false)
  1001. , m_textureSwizzleSupport(false)
  1002. , m_depthTextureSupport(false)
  1003. , m_timerQuerySupport(false)
  1004. , m_flip(false)
  1005. , m_hash( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1006. , m_backBufferFbo(0)
  1007. , m_msaaBackBufferFbo(0)
  1008. , m_ovrFbo(0)
  1009. {
  1010. memset(m_msaaBackBufferRbos, 0, sizeof(m_msaaBackBufferRbos) );
  1011. }
  1012. ~RendererContextGL()
  1013. {
  1014. }
  1015. void init()
  1016. {
  1017. m_renderdocdll = loadRenderDoc();
  1018. m_fbh.idx = invalidHandle;
  1019. memset(m_uniforms, 0, sizeof(m_uniforms) );
  1020. memset(&m_resolution, 0, sizeof(m_resolution) );
  1021. setRenderContextSize(BGFX_DEFAULT_WIDTH, BGFX_DEFAULT_HEIGHT);
  1022. // Must be after context is initialized?!
  1023. m_ovr.init();
  1024. m_vendor = getGLString(GL_VENDOR);
  1025. m_renderer = getGLString(GL_RENDERER);
  1026. m_version = getGLString(GL_VERSION);
  1027. m_glslVersion = getGLString(GL_SHADING_LANGUAGE_VERSION);
  1028. GLint numCmpFormats = 0;
  1029. GL_CHECK(glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &numCmpFormats) );
  1030. BX_TRACE("GL_NUM_COMPRESSED_TEXTURE_FORMATS %d", numCmpFormats);
  1031. GLint* cmpFormat = NULL;
  1032. if (0 < numCmpFormats)
  1033. {
  1034. numCmpFormats = numCmpFormats > 256 ? 256 : numCmpFormats;
  1035. cmpFormat = (GLint*)alloca(sizeof(GLint)*numCmpFormats);
  1036. GL_CHECK(glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, cmpFormat) );
  1037. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1038. {
  1039. GLint internalFmt = cmpFormat[ii];
  1040. uint32_t fmt = uint32_t(TextureFormat::Unknown);
  1041. for (uint32_t jj = 0; jj < fmt; ++jj)
  1042. {
  1043. if (s_textureFormat[jj].m_internalFmt == (GLenum)internalFmt)
  1044. {
  1045. s_textureFormat[jj].m_supported = true;
  1046. fmt = jj;
  1047. }
  1048. }
  1049. BX_TRACE(" %3d: %8x %s", ii, internalFmt, getName( (TextureFormat::Enum)fmt) );
  1050. }
  1051. }
  1052. if (BX_ENABLED(BGFX_CONFIG_DEBUG) )
  1053. {
  1054. #define GL_GET(_pname, _min) BX_TRACE(" " #_pname " %d (min: %d)", glGet(_pname), _min)
  1055. BX_TRACE("Defaults:");
  1056. #if BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1057. GL_GET(GL_MAX_FRAGMENT_UNIFORM_VECTORS, 16);
  1058. GL_GET(GL_MAX_VERTEX_UNIFORM_VECTORS, 128);
  1059. GL_GET(GL_MAX_VARYING_VECTORS, 8);
  1060. #else
  1061. GL_GET(GL_MAX_FRAGMENT_UNIFORM_COMPONENTS, 16 * 4);
  1062. GL_GET(GL_MAX_VERTEX_UNIFORM_COMPONENTS, 128 * 4);
  1063. GL_GET(GL_MAX_VARYING_FLOATS, 8 * 4);
  1064. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 41 || BGFX_CONFIG_RENDERER_OPENGLES
  1065. GL_GET(GL_MAX_VERTEX_ATTRIBS, 8);
  1066. GL_GET(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 8);
  1067. GL_GET(GL_MAX_CUBE_MAP_TEXTURE_SIZE, 16);
  1068. GL_GET(GL_MAX_TEXTURE_IMAGE_UNITS, 8);
  1069. GL_GET(GL_MAX_TEXTURE_SIZE, 64);
  1070. GL_GET(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0);
  1071. GL_GET(GL_MAX_RENDERBUFFER_SIZE, 1);
  1072. #undef GL_GET
  1073. BX_TRACE(" Vendor: %s", m_vendor);
  1074. BX_TRACE(" Renderer: %s", m_renderer);
  1075. BX_TRACE(" Version: %s", m_version);
  1076. BX_TRACE("GLSL version: %s", m_glslVersion);
  1077. }
  1078. // Initial binary shader hash depends on driver version.
  1079. m_hash = ( (BX_PLATFORM_WINDOWS<<1) | BX_ARCH_64BIT)
  1080. ^ (uint64_t(getGLStringHash(GL_VENDOR ) )<<32)
  1081. ^ (uint64_t(getGLStringHash(GL_RENDERER) )<<0 )
  1082. ^ (uint64_t(getGLStringHash(GL_VERSION ) )<<16)
  1083. ;
  1084. if (BX_ENABLED(BGFX_CONFIG_RENDERER_USE_EXTENSIONS) )
  1085. {
  1086. const char* extensions = (const char*)glGetString(GL_EXTENSIONS);
  1087. glGetError(); // ignore error if glGetString returns NULL.
  1088. if (NULL != extensions)
  1089. {
  1090. char name[1024];
  1091. const char* pos = extensions;
  1092. const char* end = extensions + strlen(extensions);
  1093. uint32_t index = 0;
  1094. while (pos < end)
  1095. {
  1096. uint32_t len;
  1097. const char* space = strchr(pos, ' ');
  1098. if (NULL != space)
  1099. {
  1100. len = bx::uint32_min(sizeof(name), (uint32_t)(space - pos) );
  1101. }
  1102. else
  1103. {
  1104. len = bx::uint32_min(sizeof(name), (uint32_t)strlen(pos) );
  1105. }
  1106. strncpy(name, pos, len);
  1107. name[len] = '\0';
  1108. bool supported = false;
  1109. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1110. {
  1111. Extension& extension = s_extension[ii];
  1112. if (!extension.m_supported
  1113. && extension.m_initialize)
  1114. {
  1115. const char* ext = name;
  1116. if (0 == strncmp(ext, "GL_", 3) ) // skip GL_
  1117. {
  1118. ext += 3;
  1119. }
  1120. if (0 == strcmp(ext, extension.m_name) )
  1121. {
  1122. extension.m_supported = true;
  1123. supported = true;
  1124. break;
  1125. }
  1126. }
  1127. }
  1128. BX_TRACE("GL_EXTENSION %3d%s: %s", index, supported ? " (supported)" : "", name);
  1129. BX_UNUSED(supported);
  1130. pos += len+1;
  1131. ++index;
  1132. }
  1133. BX_TRACE("Supported extensions:");
  1134. for (uint32_t ii = 0; ii < Extension::Count; ++ii)
  1135. {
  1136. if (s_extension[ii].m_supported)
  1137. {
  1138. BX_TRACE("\t%2d: %s", ii, s_extension[ii].m_name);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. // Allow all texture filters.
  1144. memset(s_textureFilter, true, BX_COUNTOF(s_textureFilter) );
  1145. bool bc123Supported = 0
  1146. || s_extension[Extension::EXT_texture_compression_s3tc ].m_supported
  1147. || s_extension[Extension::MOZ_WEBGL_compressed_texture_s3tc ].m_supported
  1148. || s_extension[Extension::WEBGL_compressed_texture_s3tc ].m_supported
  1149. || s_extension[Extension::WEBKIT_WEBGL_compressed_texture_s3tc].m_supported
  1150. ;
  1151. s_textureFormat[TextureFormat::BC1].m_supported |= bc123Supported
  1152. || s_extension[Extension::ANGLE_texture_compression_dxt1].m_supported
  1153. || s_extension[Extension::EXT_texture_compression_dxt1 ].m_supported
  1154. ;
  1155. if (!s_textureFormat[TextureFormat::BC1].m_supported
  1156. && ( s_textureFormat[TextureFormat::BC2].m_supported || s_textureFormat[TextureFormat::BC3].m_supported) )
  1157. {
  1158. // If RGBA_S3TC_DXT1 is not supported, maybe RGB_S3TC_DXT1 is?
  1159. for (GLint ii = 0; ii < numCmpFormats; ++ii)
  1160. {
  1161. if (GL_COMPRESSED_RGB_S3TC_DXT1_EXT == cmpFormat[ii])
  1162. {
  1163. setTextureFormat(TextureFormat::BC1, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB_S3TC_DXT1_EXT);
  1164. s_textureFormat[TextureFormat::BC1].m_supported = true;
  1165. break;
  1166. }
  1167. }
  1168. }
  1169. s_textureFormat[TextureFormat::BC2].m_supported |= bc123Supported
  1170. || s_extension[Extension::ANGLE_texture_compression_dxt3 ].m_supported
  1171. || s_extension[Extension::CHROMIUM_texture_compression_dxt3].m_supported
  1172. ;
  1173. s_textureFormat[TextureFormat::BC3].m_supported |= bc123Supported
  1174. || s_extension[Extension::ANGLE_texture_compression_dxt5 ].m_supported
  1175. || s_extension[Extension::CHROMIUM_texture_compression_dxt5].m_supported
  1176. ;
  1177. if (s_extension[Extension::EXT_texture_compression_latc].m_supported)
  1178. {
  1179. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_COMPRESSED_LUMINANCE_LATC1_EXT);
  1180. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT);
  1181. }
  1182. if (s_extension[Extension::ARB_texture_compression_rgtc].m_supported
  1183. || s_extension[Extension::EXT_texture_compression_rgtc].m_supported)
  1184. {
  1185. setTextureFormat(TextureFormat::BC4, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1);
  1186. setTextureFormat(TextureFormat::BC5, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2);
  1187. }
  1188. bool etc1Supported = 0
  1189. || s_extension[Extension::OES_compressed_ETC1_RGB8_texture].m_supported
  1190. || s_extension[Extension::WEBGL_compressed_texture_etc1 ].m_supported
  1191. ;
  1192. s_textureFormat[TextureFormat::ETC1].m_supported |= etc1Supported;
  1193. bool etc2Supported = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1194. || s_extension[Extension::ARB_ES3_compatibility].m_supported
  1195. ;
  1196. s_textureFormat[TextureFormat::ETC2 ].m_supported |= etc2Supported;
  1197. s_textureFormat[TextureFormat::ETC2A ].m_supported |= etc2Supported;
  1198. s_textureFormat[TextureFormat::ETC2A1].m_supported |= etc2Supported;
  1199. if (!s_textureFormat[TextureFormat::ETC1].m_supported
  1200. && s_textureFormat[TextureFormat::ETC2].m_supported)
  1201. {
  1202. // When ETC2 is supported override ETC1 texture format settings.
  1203. s_textureFormat[TextureFormat::ETC1].m_internalFmt = GL_COMPRESSED_RGB8_ETC2;
  1204. s_textureFormat[TextureFormat::ETC1].m_fmt = GL_COMPRESSED_RGB8_ETC2;
  1205. s_textureFormat[TextureFormat::ETC1].m_supported = true;
  1206. }
  1207. bool ptc1Supported = 0
  1208. || s_extension[Extension::IMG_texture_compression_pvrtc ].m_supported
  1209. || s_extension[Extension::WEBGL_compressed_texture_pvrtc].m_supported
  1210. ;
  1211. s_textureFormat[TextureFormat::PTC12 ].m_supported |= ptc1Supported;
  1212. s_textureFormat[TextureFormat::PTC14 ].m_supported |= ptc1Supported;
  1213. s_textureFormat[TextureFormat::PTC12A].m_supported |= ptc1Supported;
  1214. s_textureFormat[TextureFormat::PTC14A].m_supported |= ptc1Supported;
  1215. bool ptc2Supported = s_extension[Extension::IMG_texture_compression_pvrtc2].m_supported;
  1216. s_textureFormat[TextureFormat::PTC22].m_supported |= ptc2Supported;
  1217. s_textureFormat[TextureFormat::PTC24].m_supported |= ptc2Supported;
  1218. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES) )
  1219. {
  1220. setTextureFormat(TextureFormat::D32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT);
  1221. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  1222. {
  1223. setTextureFormat(TextureFormat::RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT);
  1224. // internalFormat and format must match:
  1225. // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glTexImage2D.xml
  1226. setTextureFormat(TextureFormat::RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE);
  1227. setTextureFormat(TextureFormat::R5G6B5, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5);
  1228. setTextureFormat(TextureFormat::RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4);
  1229. setTextureFormat(TextureFormat::RGB5A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1);
  1230. if (s_extension[Extension::OES_texture_half_float].m_supported
  1231. || s_extension[Extension::OES_texture_float ].m_supported)
  1232. {
  1233. // https://www.khronos.org/registry/gles/extensions/OES/OES_texture_float.txt
  1234. // When half/float is available via extensions texture will be marked as
  1235. // incomplete if it uses anything other than nearest filter.
  1236. const bool linear16F = s_extension[Extension::OES_texture_half_float_linear].m_supported;
  1237. const bool linear32F = s_extension[Extension::OES_texture_float_linear ].m_supported;
  1238. s_textureFilter[TextureFormat::R16F] = linear16F;
  1239. s_textureFilter[TextureFormat::RG16F] = linear16F;
  1240. s_textureFilter[TextureFormat::RGBA16F] = linear16F;
  1241. s_textureFilter[TextureFormat::R32F] = linear32F;
  1242. s_textureFilter[TextureFormat::RG32F] = linear32F;
  1243. s_textureFilter[TextureFormat::RGBA32F] = linear32F;
  1244. }
  1245. if (BX_ENABLED(BX_PLATFORM_IOS) )
  1246. {
  1247. setTextureFormat(TextureFormat::D16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT);
  1248. setTextureFormat(TextureFormat::D24S8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8);
  1249. }
  1250. }
  1251. }
  1252. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1253. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1254. {
  1255. setTextureFormat(TextureFormat::R16, GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT);
  1256. setTextureFormat(TextureFormat::RG16, GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT);
  1257. setTextureFormat(TextureFormat::RGBA16, GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT);
  1258. setTextureFormat(TextureFormat::R32, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT);
  1259. setTextureFormat(TextureFormat::RG32, GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT);
  1260. setTextureFormat(TextureFormat::RGBA32, GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT);
  1261. }
  1262. if (s_extension[Extension::EXT_texture_format_BGRA8888 ].m_supported
  1263. || s_extension[Extension::EXT_bgra ].m_supported
  1264. || s_extension[Extension::IMG_texture_format_BGRA8888 ].m_supported
  1265. || s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1266. {
  1267. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1268. {
  1269. m_readPixelsFmt = GL_BGRA;
  1270. }
  1271. // Mixing GLES and GL extensions here. OpenGL EXT_bgra and
  1272. // APPLE_texture_format_BGRA8888 wants
  1273. // format to be BGRA but internal format to stay RGBA, but
  1274. // EXT_texture_format_BGRA8888 wants both format and internal
  1275. // format to be BGRA.
  1276. //
  1277. // Reference:
  1278. // https://www.khronos.org/registry/gles/extensions/EXT/EXT_texture_format_BGRA8888.txt
  1279. // https://www.opengl.org/registry/specs/EXT/bgra.txt
  1280. // https://www.khronos.org/registry/gles/extensions/APPLE/APPLE_texture_format_BGRA8888.txt
  1281. if (!s_extension[Extension::EXT_bgra ].m_supported
  1282. && !s_extension[Extension::APPLE_texture_format_BGRA8888].m_supported)
  1283. {
  1284. s_textureFormat[TextureFormat::BGRA8].m_internalFmt = GL_BGRA;
  1285. }
  1286. if (!isTextureFormatValid(TextureFormat::BGRA8) )
  1287. {
  1288. // Revert back to RGBA if texture can't be created.
  1289. setTextureFormat(TextureFormat::BGRA8, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE);
  1290. }
  1291. }
  1292. if (BX_ENABLED(BX_PLATFORM_EMSCRIPTEN)
  1293. || !isTextureFormatValid(TextureFormat::R8) )
  1294. {
  1295. // GL core has to use GL_R8 Issue#208, GLES2 has to use GL_LUMINANCE issue#226
  1296. s_textureFormat[TextureFormat::R8].m_internalFmt = GL_LUMINANCE;
  1297. s_textureFormat[TextureFormat::R8].m_fmt = GL_LUMINANCE;
  1298. }
  1299. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1300. {
  1301. if (TextureFormat::Unknown != ii
  1302. && TextureFormat::UnknownDepth != ii)
  1303. {
  1304. s_textureFormat[ii].m_supported = isTextureFormatValid(TextureFormat::Enum(ii) );
  1305. }
  1306. }
  1307. if (BX_ENABLED(0) )
  1308. {
  1309. // Disable all compressed texture formats. For testing only.
  1310. for (uint32_t ii = 0; ii < TextureFormat::Unknown; ++ii)
  1311. {
  1312. s_textureFormat[ii].m_supported = false;
  1313. }
  1314. }
  1315. const bool computeSupport = false
  1316. || !!(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  1317. || s_extension[Extension::ARB_compute_shader].m_supported
  1318. ;
  1319. for (uint32_t ii = 0; ii < TextureFormat::Count; ++ii)
  1320. {
  1321. uint8_t supported = 0;
  1322. supported |= s_textureFormat[ii].m_supported
  1323. ? BGFX_CAPS_FORMAT_TEXTURE_COLOR
  1324. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1325. ;
  1326. supported |= isTextureFormatValid(TextureFormat::Enum(ii), true)
  1327. ? BGFX_CAPS_FORMAT_TEXTURE_COLOR_SRGB
  1328. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1329. ;
  1330. supported |= computeSupport
  1331. && isImageFormatValid(TextureFormat::Enum(ii) )
  1332. ? BGFX_CAPS_FORMAT_TEXTURE_IMAGE
  1333. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1334. ;
  1335. supported |= isFramebufferFormatValid(TextureFormat::Enum(ii) )
  1336. ? BGFX_CAPS_FORMAT_TEXTURE_FRAMEBUFFER
  1337. : BGFX_CAPS_FORMAT_TEXTURE_NONE
  1338. ;
  1339. g_caps.formats[ii] = supported;
  1340. }
  1341. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1342. || s_extension[Extension::OES_texture_3D].m_supported
  1343. ? BGFX_CAPS_TEXTURE_3D
  1344. : 0
  1345. ;
  1346. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1347. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1348. ? BGFX_CAPS_TEXTURE_COMPARE_ALL
  1349. : 0
  1350. ;
  1351. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1352. || s_extension[Extension::OES_vertex_half_float].m_supported
  1353. ? BGFX_CAPS_VERTEX_ATTRIB_HALF
  1354. : 0
  1355. ;
  1356. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1357. || s_extension[Extension::EXT_frag_depth].m_supported
  1358. ? BGFX_CAPS_FRAGMENT_DEPTH
  1359. : 0
  1360. ;
  1361. g_caps.supported |= s_extension[Extension::ARB_draw_buffers_blend].m_supported
  1362. ? BGFX_CAPS_BLEND_INDEPENDENT
  1363. : 0
  1364. ;
  1365. g_caps.supported |= s_extension[Extension::INTEL_fragment_shader_ordering].m_supported
  1366. ? BGFX_CAPS_FRAGMENT_ORDERING
  1367. : 0
  1368. ;
  1369. g_caps.supported |= !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1370. || s_extension[Extension::OES_element_index_uint].m_supported
  1371. ? BGFX_CAPS_INDEX32
  1372. : 0
  1373. ;
  1374. const bool drawIndirectSupported = false
  1375. || s_extension[Extension::AMD_multi_draw_indirect].m_supported
  1376. || s_extension[Extension::ARB_draw_indirect ].m_supported
  1377. || s_extension[Extension::ARB_multi_draw_indirect].m_supported
  1378. || s_extension[Extension::EXT_multi_draw_indirect].m_supported
  1379. ;
  1380. if (drawIndirectSupported)
  1381. {
  1382. if (NULL == glMultiDrawArraysIndirect
  1383. || NULL == glMultiDrawElementsIndirect)
  1384. {
  1385. glMultiDrawArraysIndirect = stubMultiDrawArraysIndirect;
  1386. glMultiDrawElementsIndirect = stubMultiDrawElementsIndirect;
  1387. }
  1388. }
  1389. g_caps.supported |= drawIndirectSupported
  1390. ? BGFX_CAPS_DRAW_INDIRECT
  1391. : 0
  1392. ;
  1393. g_caps.maxTextureSize = uint16_t(glGet(GL_MAX_TEXTURE_SIZE) );
  1394. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1395. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1396. || s_extension[Extension::EXT_draw_buffers ].m_supported
  1397. || s_extension[Extension::WEBGL_draw_buffers].m_supported)
  1398. {
  1399. g_caps.maxFBAttachments = uint8_t(bx::uint32_min(glGet(GL_MAX_COLOR_ATTACHMENTS), BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS) );
  1400. }
  1401. m_vaoSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1402. || s_extension[Extension::ARB_vertex_array_object].m_supported
  1403. || s_extension[Extension::OES_vertex_array_object].m_supported
  1404. ;
  1405. if (BX_ENABLED(BX_PLATFORM_NACL) )
  1406. {
  1407. m_vaoSupport &= true
  1408. && NULL != glGenVertexArrays
  1409. && NULL != glDeleteVertexArrays
  1410. && NULL != glBindVertexArray
  1411. ;
  1412. }
  1413. if (m_vaoSupport)
  1414. {
  1415. GL_CHECK(glGenVertexArrays(1, &m_vao) );
  1416. }
  1417. m_samplerObjectSupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1418. || s_extension[Extension::ARB_sampler_objects].m_supported
  1419. ;
  1420. m_shadowSamplersSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1421. || s_extension[Extension::EXT_shadow_samplers].m_supported
  1422. ;
  1423. m_programBinarySupport = !!(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1424. || s_extension[Extension::ARB_get_program_binary].m_supported
  1425. || s_extension[Extension::OES_get_program_binary].m_supported
  1426. || s_extension[Extension::IMG_shader_binary ].m_supported
  1427. ;
  1428. m_textureSwizzleSupport = false
  1429. || s_extension[Extension::ARB_texture_swizzle].m_supported
  1430. || s_extension[Extension::EXT_texture_swizzle].m_supported
  1431. ;
  1432. m_depthTextureSupport = !!(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1433. || s_extension[Extension::ANGLE_depth_texture ].m_supported
  1434. || s_extension[Extension::CHROMIUM_depth_texture ].m_supported
  1435. || s_extension[Extension::GOOGLE_depth_texture ].m_supported
  1436. || s_extension[Extension::OES_depth_texture ].m_supported
  1437. || s_extension[Extension::MOZ_WEBGL_depth_texture ].m_supported
  1438. || s_extension[Extension::WEBGL_depth_texture ].m_supported
  1439. || s_extension[Extension::WEBKIT_WEBGL_depth_texture].m_supported
  1440. ;
  1441. m_timerQuerySupport = 0
  1442. || s_extension[Extension::ANGLE_timer_query ].m_supported
  1443. || s_extension[Extension::ARB_timer_query ].m_supported
  1444. || s_extension[Extension::EXT_disjoint_timer_query].m_supported
  1445. || s_extension[Extension::EXT_timer_query ].m_supported
  1446. ;
  1447. m_timerQuerySupport &= NULL != glGetQueryObjectui64v;
  1448. g_caps.supported |= m_depthTextureSupport
  1449. ? BGFX_CAPS_TEXTURE_COMPARE_LEQUAL
  1450. : 0
  1451. ;
  1452. g_caps.supported |= computeSupport
  1453. ? BGFX_CAPS_COMPUTE
  1454. : 0
  1455. ;
  1456. g_caps.supported |= GlContext::isSwapChainSupported()
  1457. ? BGFX_CAPS_SWAP_CHAIN
  1458. : 0
  1459. ;
  1460. if (s_extension[Extension::EXT_texture_filter_anisotropic].m_supported)
  1461. {
  1462. GL_CHECK(glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &m_maxAnisotropyDefault) );
  1463. }
  1464. if (s_extension[Extension::ARB_texture_multisample].m_supported
  1465. || s_extension[Extension::ANGLE_framebuffer_multisample].m_supported)
  1466. {
  1467. GL_CHECK(glGetIntegerv(GL_MAX_SAMPLES, &m_maxMsaa) );
  1468. }
  1469. if (s_extension[Extension::OES_read_format].m_supported
  1470. && (s_extension[Extension::IMG_read_format].m_supported || s_extension[Extension::EXT_read_format_bgra].m_supported) )
  1471. {
  1472. m_readPixelsFmt = GL_BGRA;
  1473. }
  1474. else
  1475. {
  1476. m_readPixelsFmt = GL_RGBA;
  1477. }
  1478. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  1479. {
  1480. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1481. }
  1482. else
  1483. {
  1484. if (!BX_ENABLED(BX_PLATFORM_IOS) )
  1485. {
  1486. if (s_extension[Extension::ARB_instanced_arrays].m_supported
  1487. || s_extension[Extension::ANGLE_instanced_arrays].m_supported)
  1488. {
  1489. if (NULL != glVertexAttribDivisor
  1490. && NULL != glDrawArraysInstanced
  1491. && NULL != glDrawElementsInstanced)
  1492. {
  1493. g_caps.supported |= BGFX_CAPS_INSTANCING;
  1494. }
  1495. }
  1496. }
  1497. if (0 == (g_caps.supported & BGFX_CAPS_INSTANCING) )
  1498. {
  1499. glVertexAttribDivisor = stubVertexAttribDivisor;
  1500. glDrawArraysInstanced = stubDrawArraysInstanced;
  1501. glDrawElementsInstanced = stubDrawElementsInstanced;
  1502. }
  1503. }
  1504. if (s_extension[Extension::ARB_debug_output].m_supported
  1505. || s_extension[Extension::KHR_debug].m_supported)
  1506. {
  1507. if (NULL != glDebugMessageControl
  1508. && NULL != glDebugMessageInsert
  1509. && NULL != glDebugMessageCallback
  1510. && NULL != glGetDebugMessageLog)
  1511. {
  1512. GL_CHECK(glDebugMessageCallback(debugProcCb, NULL) );
  1513. GL_CHECK(glDebugMessageControl(GL_DONT_CARE
  1514. , GL_DONT_CARE
  1515. , GL_DEBUG_SEVERITY_MEDIUM
  1516. , 0
  1517. , NULL
  1518. , GL_TRUE
  1519. ) );
  1520. }
  1521. }
  1522. if (s_extension[Extension::ARB_seamless_cube_map].m_supported)
  1523. {
  1524. GL_CHECK(glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS) );
  1525. }
  1526. if (s_extension[Extension::ARB_depth_clamp].m_supported)
  1527. {
  1528. GL_CHECK(glEnable(GL_DEPTH_CLAMP) );
  1529. }
  1530. if (NULL == glFrameTerminatorGREMEDY
  1531. || !s_extension[Extension::GREMEDY_frame_terminator].m_supported)
  1532. {
  1533. glFrameTerminatorGREMEDY = stubFrameTerminatorGREMEDY;
  1534. }
  1535. if (NULL == glInsertEventMarker
  1536. || !s_extension[Extension::EXT_debug_marker].m_supported)
  1537. {
  1538. glInsertEventMarker = (NULL != glStringMarkerGREMEDY && s_extension[Extension::GREMEDY_string_marker].m_supported)
  1539. ? stubInsertEventMarkerGREMEDY
  1540. : stubInsertEventMarker
  1541. ;
  1542. }
  1543. setGraphicsDebuggerPresent(s_extension[Extension::EXT_debug_tool].m_supported);
  1544. if (NULL == glObjectLabel)
  1545. {
  1546. glObjectLabel = stubObjectLabel;
  1547. }
  1548. if (NULL == glInvalidateFramebuffer)
  1549. {
  1550. glInvalidateFramebuffer = stubInvalidateFramebuffer;
  1551. }
  1552. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1553. && m_timerQuerySupport)
  1554. {
  1555. m_queries.create();
  1556. }
  1557. // Init reserved part of view name.
  1558. for (uint32_t ii = 0; ii < BGFX_CONFIG_MAX_VIEWS; ++ii)
  1559. {
  1560. bx::snprintf(s_viewName[ii], BGFX_CONFIG_MAX_VIEW_NAME_RESERVED+1, "%3d ", ii);
  1561. }
  1562. ovrPostReset();
  1563. }
  1564. void shutdown()
  1565. {
  1566. ovrPreReset();
  1567. m_ovr.shutdown();
  1568. if (m_vaoSupport)
  1569. {
  1570. GL_CHECK(glBindVertexArray(0) );
  1571. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  1572. m_vao = 0;
  1573. }
  1574. captureFinish();
  1575. invalidateCache();
  1576. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  1577. && m_timerQuerySupport)
  1578. {
  1579. m_queries.destroy();
  1580. }
  1581. destroyMsaaFbo();
  1582. m_glctx.destroy();
  1583. m_flip = false;
  1584. unloadRenderDoc(m_renderdocdll);
  1585. }
  1586. RendererType::Enum getRendererType() const BX_OVERRIDE
  1587. {
  1588. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  1589. {
  1590. return RendererType::OpenGL;
  1591. }
  1592. return RendererType::OpenGLES;
  1593. }
  1594. const char* getRendererName() const BX_OVERRIDE
  1595. {
  1596. return BGFX_RENDERER_OPENGL_NAME;
  1597. }
  1598. void flip(HMD& _hmd)
  1599. {
  1600. if (m_flip)
  1601. {
  1602. for (uint32_t ii = 1, num = m_numWindows; ii < num; ++ii)
  1603. {
  1604. m_glctx.swap(m_frameBuffers[m_windows[ii].idx].m_swapChain);
  1605. }
  1606. if (!m_ovr.swap(_hmd) )
  1607. {
  1608. m_glctx.swap();
  1609. }
  1610. }
  1611. }
  1612. void createIndexBuffer(IndexBufferHandle _handle, Memory* _mem, uint16_t _flags) BX_OVERRIDE
  1613. {
  1614. m_indexBuffers[_handle.idx].create(_mem->size, _mem->data, _flags);
  1615. }
  1616. void destroyIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1617. {
  1618. m_indexBuffers[_handle.idx].destroy();
  1619. }
  1620. void createVertexDecl(VertexDeclHandle _handle, const VertexDecl& _decl) BX_OVERRIDE
  1621. {
  1622. VertexDecl& decl = m_vertexDecls[_handle.idx];
  1623. memcpy(&decl, &_decl, sizeof(VertexDecl) );
  1624. dump(decl);
  1625. }
  1626. void destroyVertexDecl(VertexDeclHandle /*_handle*/) BX_OVERRIDE
  1627. {
  1628. }
  1629. void createVertexBuffer(VertexBufferHandle _handle, Memory* _mem, VertexDeclHandle _declHandle, uint16_t _flags) BX_OVERRIDE
  1630. {
  1631. m_vertexBuffers[_handle.idx].create(_mem->size, _mem->data, _declHandle, _flags);
  1632. }
  1633. void destroyVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1634. {
  1635. m_vertexBuffers[_handle.idx].destroy();
  1636. }
  1637. void createDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  1638. {
  1639. m_indexBuffers[_handle.idx].create(_size, NULL, _flags);
  1640. }
  1641. void updateDynamicIndexBuffer(IndexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1642. {
  1643. m_indexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1644. }
  1645. void destroyDynamicIndexBuffer(IndexBufferHandle _handle) BX_OVERRIDE
  1646. {
  1647. m_indexBuffers[_handle.idx].destroy();
  1648. }
  1649. void createDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _size, uint16_t _flags) BX_OVERRIDE
  1650. {
  1651. VertexDeclHandle decl = BGFX_INVALID_HANDLE;
  1652. m_vertexBuffers[_handle.idx].create(_size, NULL, decl, _flags);
  1653. }
  1654. void updateDynamicVertexBuffer(VertexBufferHandle _handle, uint32_t _offset, uint32_t _size, Memory* _mem) BX_OVERRIDE
  1655. {
  1656. m_vertexBuffers[_handle.idx].update(_offset, bx::uint32_min(_size, _mem->size), _mem->data);
  1657. }
  1658. void destroyDynamicVertexBuffer(VertexBufferHandle _handle) BX_OVERRIDE
  1659. {
  1660. m_vertexBuffers[_handle.idx].destroy();
  1661. }
  1662. void createShader(ShaderHandle _handle, Memory* _mem) BX_OVERRIDE
  1663. {
  1664. m_shaders[_handle.idx].create(_mem);
  1665. }
  1666. void destroyShader(ShaderHandle _handle) BX_OVERRIDE
  1667. {
  1668. m_shaders[_handle.idx].destroy();
  1669. }
  1670. void createProgram(ProgramHandle _handle, ShaderHandle _vsh, ShaderHandle _fsh) BX_OVERRIDE
  1671. {
  1672. ShaderGL dummyFragmentShader;
  1673. m_program[_handle.idx].create(m_shaders[_vsh.idx], isValid(_fsh) ? m_shaders[_fsh.idx] : dummyFragmentShader);
  1674. }
  1675. void destroyProgram(ProgramHandle _handle) BX_OVERRIDE
  1676. {
  1677. m_program[_handle.idx].destroy();
  1678. }
  1679. void createTexture(TextureHandle _handle, Memory* _mem, uint32_t _flags, uint8_t _skip) BX_OVERRIDE
  1680. {
  1681. m_textures[_handle.idx].create(_mem, _flags, _skip);
  1682. }
  1683. void updateTextureBegin(TextureHandle /*_handle*/, uint8_t /*_side*/, uint8_t /*_mip*/) BX_OVERRIDE
  1684. {
  1685. }
  1686. 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
  1687. {
  1688. m_textures[_handle.idx].update(_side, _mip, _rect, _z, _depth, _pitch, _mem);
  1689. }
  1690. void updateTextureEnd() BX_OVERRIDE
  1691. {
  1692. }
  1693. void resizeTexture(TextureHandle _handle, uint16_t _width, uint16_t _height) BX_OVERRIDE
  1694. {
  1695. TextureGL& texture = m_textures[_handle.idx];
  1696. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  1697. const Memory* mem = alloc(size);
  1698. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  1699. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  1700. bx::write(&writer, magic);
  1701. TextureCreate tc;
  1702. tc.m_flags = texture.m_flags;
  1703. tc.m_width = _width;
  1704. tc.m_height = _height;
  1705. tc.m_sides = 0;
  1706. tc.m_depth = 0;
  1707. tc.m_numMips = 1;
  1708. tc.m_format = texture.m_requestedFormat;
  1709. tc.m_cubeMap = false;
  1710. tc.m_mem = NULL;
  1711. bx::write(&writer, tc);
  1712. texture.destroy();
  1713. texture.create(mem, tc.m_flags, 0);
  1714. release(mem);
  1715. }
  1716. void destroyTexture(TextureHandle _handle) BX_OVERRIDE
  1717. {
  1718. m_textures[_handle.idx].destroy();
  1719. }
  1720. void createFrameBuffer(FrameBufferHandle _handle, uint8_t _num, const TextureHandle* _textureHandles) BX_OVERRIDE
  1721. {
  1722. m_frameBuffers[_handle.idx].create(_num, _textureHandles);
  1723. }
  1724. void createFrameBuffer(FrameBufferHandle _handle, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat) BX_OVERRIDE
  1725. {
  1726. uint16_t denseIdx = m_numWindows++;
  1727. m_windows[denseIdx] = _handle;
  1728. m_frameBuffers[_handle.idx].create(denseIdx, _nwh, _width, _height, _depthFormat);
  1729. }
  1730. void destroyFrameBuffer(FrameBufferHandle _handle) BX_OVERRIDE
  1731. {
  1732. uint16_t denseIdx = m_frameBuffers[_handle.idx].destroy();
  1733. if (UINT16_MAX != denseIdx)
  1734. {
  1735. --m_numWindows;
  1736. if (m_numWindows > 1)
  1737. {
  1738. FrameBufferHandle handle = m_windows[m_numWindows];
  1739. m_windows[denseIdx] = handle;
  1740. m_frameBuffers[handle.idx].m_denseIdx = denseIdx;
  1741. }
  1742. }
  1743. }
  1744. void createUniform(UniformHandle _handle, UniformType::Enum _type, uint16_t _num, const char* _name) BX_OVERRIDE
  1745. {
  1746. if (NULL != m_uniforms[_handle.idx])
  1747. {
  1748. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1749. }
  1750. uint32_t size = g_uniformTypeSize[_type]*_num;
  1751. void* data = BX_ALLOC(g_allocator, size);
  1752. memset(data, 0, size);
  1753. m_uniforms[_handle.idx] = data;
  1754. m_uniformReg.add(_handle, _name, m_uniforms[_handle.idx]);
  1755. }
  1756. void destroyUniform(UniformHandle _handle) BX_OVERRIDE
  1757. {
  1758. BX_FREE(g_allocator, m_uniforms[_handle.idx]);
  1759. m_uniforms[_handle.idx] = NULL;
  1760. }
  1761. void saveScreenShot(const char* _filePath) BX_OVERRIDE
  1762. {
  1763. uint32_t length = m_resolution.m_width*m_resolution.m_height*4;
  1764. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  1765. uint32_t width = m_resolution.m_width;
  1766. uint32_t height = m_resolution.m_height;
  1767. GL_CHECK(glReadPixels(0
  1768. , 0
  1769. , width
  1770. , height
  1771. , m_readPixelsFmt
  1772. , GL_UNSIGNED_BYTE
  1773. , data
  1774. ) );
  1775. if (GL_RGBA == m_readPixelsFmt)
  1776. {
  1777. imageSwizzleBgra8(width, height, width*4, data, data);
  1778. }
  1779. g_callback->screenShot(_filePath
  1780. , width
  1781. , height
  1782. , width*4
  1783. , data
  1784. , length
  1785. , true
  1786. );
  1787. BX_FREE(g_allocator, data);
  1788. }
  1789. void updateViewName(uint8_t _id, const char* _name) BX_OVERRIDE
  1790. {
  1791. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  1792. {
  1793. bx::strlcpy(&s_viewName[_id][BGFX_CONFIG_MAX_VIEW_NAME_RESERVED]
  1794. , _name
  1795. , BX_COUNTOF(s_viewName[0])-BGFX_CONFIG_MAX_VIEW_NAME_RESERVED
  1796. );
  1797. }
  1798. }
  1799. void updateUniform(uint16_t _loc, const void* _data, uint32_t _size) BX_OVERRIDE
  1800. {
  1801. memcpy(m_uniforms[_loc], _data, _size);
  1802. }
  1803. void setMarker(const char* _marker, uint32_t _size) BX_OVERRIDE
  1804. {
  1805. GL_CHECK(glInsertEventMarker(_size, _marker) );
  1806. }
  1807. void submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter) BX_OVERRIDE;
  1808. void blitSetup(TextVideoMemBlitter& _blitter) BX_OVERRIDE
  1809. {
  1810. if (0 != m_vao)
  1811. {
  1812. GL_CHECK(glBindVertexArray(m_vao) );
  1813. }
  1814. uint32_t width = m_resolution.m_width;
  1815. uint32_t height = m_resolution.m_height;
  1816. if (m_ovr.isEnabled() )
  1817. {
  1818. m_ovr.getSize(width, height);
  1819. }
  1820. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  1821. GL_CHECK(glViewport(0, 0, width, height) );
  1822. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  1823. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  1824. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  1825. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  1826. GL_CHECK(glDisable(GL_CULL_FACE) );
  1827. GL_CHECK(glDisable(GL_BLEND) );
  1828. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  1829. ProgramGL& program = m_program[_blitter.m_program.idx];
  1830. GL_CHECK(glUseProgram(program.m_id) );
  1831. GL_CHECK(glUniform1i(program.m_sampler[0], 0) );
  1832. float proj[16];
  1833. bx::mtxOrtho(proj, 0.0f, (float)width, (float)height, 0.0f, 0.0f, 1000.0f);
  1834. GL_CHECK(glUniformMatrix4fv(program.m_predefined[0].m_loc
  1835. , 1
  1836. , GL_FALSE
  1837. , proj
  1838. ) );
  1839. GL_CHECK(glActiveTexture(GL_TEXTURE0) );
  1840. GL_CHECK(glBindTexture(GL_TEXTURE_2D, m_textures[_blitter.m_texture.idx].m_id) );
  1841. }
  1842. void blitRender(TextVideoMemBlitter& _blitter, uint32_t _numIndices) BX_OVERRIDE
  1843. {
  1844. const uint32_t numVertices = _numIndices*4/6;
  1845. if (0 < numVertices)
  1846. {
  1847. m_indexBuffers[_blitter.m_ib->handle.idx].update(0, _numIndices*2, _blitter.m_ib->data);
  1848. m_vertexBuffers[_blitter.m_vb->handle.idx].update(0, numVertices*_blitter.m_decl.m_stride, _blitter.m_vb->data);
  1849. VertexBufferGL& vb = m_vertexBuffers[_blitter.m_vb->handle.idx];
  1850. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  1851. IndexBufferGL& ib = m_indexBuffers[_blitter.m_ib->handle.idx];
  1852. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  1853. ProgramGL& program = m_program[_blitter.m_program.idx];
  1854. program.bindAttributes(_blitter.m_decl, 0);
  1855. GL_CHECK(glDrawElements(GL_TRIANGLES
  1856. , _numIndices
  1857. , GL_UNSIGNED_SHORT
  1858. , (void*)0
  1859. ) );
  1860. }
  1861. }
  1862. void updateResolution(const Resolution& _resolution)
  1863. {
  1864. bool recenter = !!(_resolution.m_flags & BGFX_RESET_HMD_RECENTER);
  1865. m_maxAnisotropy = !!(_resolution.m_flags & BGFX_RESET_MAXANISOTROPY)
  1866. ? m_maxAnisotropyDefault
  1867. : 0.0f
  1868. ;
  1869. uint32_t flags = _resolution.m_flags & ~(BGFX_RESET_HMD_RECENTER | BGFX_RESET_MAXANISOTROPY);
  1870. if (m_resolution.m_width != _resolution.m_width
  1871. || m_resolution.m_height != _resolution.m_height
  1872. || m_resolution.m_flags != flags)
  1873. {
  1874. m_textVideoMem.resize(false, _resolution.m_width, _resolution.m_height);
  1875. m_textVideoMem.clear();
  1876. m_resolution = _resolution;
  1877. m_resolution.m_flags = flags;
  1878. if ( (flags & BGFX_RESET_HMD)
  1879. && m_ovr.isInitialized() )
  1880. {
  1881. flags &= ~BGFX_RESET_MSAA_MASK;
  1882. }
  1883. setRenderContextSize(m_resolution.m_width
  1884. , m_resolution.m_height
  1885. , flags
  1886. );
  1887. updateCapture();
  1888. for (uint32_t ii = 0; ii < BX_COUNTOF(m_frameBuffers); ++ii)
  1889. {
  1890. m_frameBuffers[ii].postReset();
  1891. }
  1892. ovrPreReset();
  1893. ovrPostReset();
  1894. }
  1895. if (recenter)
  1896. {
  1897. m_ovr.recenter();
  1898. }
  1899. }
  1900. void setShaderUniform4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1901. {
  1902. GL_CHECK(glUniform4fv(_regIndex
  1903. , _numRegs
  1904. , (const GLfloat*)_val
  1905. ) );
  1906. }
  1907. void setShaderUniform4x4f(uint8_t /*_flags*/, uint32_t _regIndex, const void* _val, uint32_t _numRegs)
  1908. {
  1909. GL_CHECK(glUniformMatrix4fv(_regIndex
  1910. , _numRegs
  1911. , GL_FALSE
  1912. , (const GLfloat*)_val
  1913. ) );
  1914. }
  1915. uint32_t setFrameBuffer(FrameBufferHandle _fbh, uint32_t _height, uint16_t _discard = BGFX_CLEAR_NONE, bool _msaa = true)
  1916. {
  1917. if (isValid(m_fbh)
  1918. && m_fbh.idx != _fbh.idx
  1919. && (BGFX_CLEAR_NONE != m_fbDiscard || m_rtMsaa) )
  1920. {
  1921. FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  1922. if (m_rtMsaa)
  1923. {
  1924. frameBuffer.resolve();
  1925. }
  1926. if (BGFX_CLEAR_NONE != m_fbDiscard)
  1927. {
  1928. frameBuffer.discard(m_fbDiscard);
  1929. }
  1930. m_fbDiscard = BGFX_CLEAR_NONE;
  1931. }
  1932. m_glctx.makeCurrent(NULL);
  1933. if (!isValid(_fbh) )
  1934. {
  1935. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1936. }
  1937. else
  1938. {
  1939. FrameBufferGL& frameBuffer = m_frameBuffers[_fbh.idx];
  1940. _height = frameBuffer.m_height;
  1941. if (UINT16_MAX != frameBuffer.m_denseIdx)
  1942. {
  1943. m_glctx.makeCurrent(frameBuffer.m_swapChain);
  1944. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  1945. }
  1946. else
  1947. {
  1948. m_glctx.makeCurrent(NULL);
  1949. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer.m_fbo[0]) );
  1950. }
  1951. }
  1952. m_fbh = _fbh;
  1953. m_fbDiscard = _discard;
  1954. m_rtMsaa = _msaa;
  1955. return _height;
  1956. }
  1957. uint32_t getNumRt() const
  1958. {
  1959. if (isValid(m_fbh) )
  1960. {
  1961. const FrameBufferGL& frameBuffer = m_frameBuffers[m_fbh.idx];
  1962. return frameBuffer.m_num;
  1963. }
  1964. return 1;
  1965. }
  1966. void createMsaaFbo(uint32_t _width, uint32_t _height, uint32_t _msaa)
  1967. {
  1968. if (0 == m_msaaBackBufferFbo // iOS
  1969. && 1 < _msaa)
  1970. {
  1971. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  1972. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1973. GL_CHECK(glGenRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  1974. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  1975. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_RGBA8, _width, _height) );
  1976. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  1977. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER, _msaa, GL_DEPTH24_STENCIL8, _width, _height) );
  1978. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, m_msaaBackBufferRbos[0]) );
  1979. GLenum attachment = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  1980. ? GL_DEPTH_STENCIL_ATTACHMENT
  1981. : GL_DEPTH_ATTACHMENT
  1982. ;
  1983. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, m_msaaBackBufferRbos[1]) );
  1984. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1985. , "glCheckFramebufferStatus failed 0x%08x"
  1986. , glCheckFramebufferStatus(GL_FRAMEBUFFER)
  1987. );
  1988. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  1989. }
  1990. }
  1991. void destroyMsaaFbo()
  1992. {
  1993. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  1994. && 0 != m_msaaBackBufferFbo)
  1995. {
  1996. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  1997. m_msaaBackBufferFbo = 0;
  1998. if (0 != m_msaaBackBufferRbos[0])
  1999. {
  2000. GL_CHECK(glDeleteRenderbuffers(BX_COUNTOF(m_msaaBackBufferRbos), m_msaaBackBufferRbos) );
  2001. m_msaaBackBufferRbos[0] = 0;
  2002. m_msaaBackBufferRbos[1] = 0;
  2003. }
  2004. }
  2005. }
  2006. void blitMsaaFbo()
  2007. {
  2008. if (m_backBufferFbo != m_msaaBackBufferFbo // iOS
  2009. && 0 != m_msaaBackBufferFbo)
  2010. {
  2011. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2012. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2013. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2014. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0) );
  2015. uint32_t width = m_resolution.m_width;
  2016. uint32_t height = m_resolution.m_height;
  2017. GLenum filter = BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  2018. ? GL_NEAREST
  2019. : GL_LINEAR
  2020. ;
  2021. GL_CHECK(glBlitFramebuffer(0
  2022. , 0
  2023. , width
  2024. , height
  2025. , 0
  2026. , 0
  2027. , width
  2028. , height
  2029. , GL_COLOR_BUFFER_BIT
  2030. , filter
  2031. ) );
  2032. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  2033. }
  2034. }
  2035. void setRenderContextSize(uint32_t _width, uint32_t _height, uint32_t _flags = 0)
  2036. {
  2037. if (_width != 0
  2038. || _height != 0)
  2039. {
  2040. if (!m_glctx.isValid() )
  2041. {
  2042. m_glctx.create(_width, _height);
  2043. #if BX_PLATFORM_IOS
  2044. // iOS: need to figure out how to deal with FBO created by context.
  2045. m_backBufferFbo = m_msaaBackBufferFbo = m_glctx.getFbo();
  2046. #endif // BX_PLATFORM_IOS
  2047. }
  2048. else
  2049. {
  2050. destroyMsaaFbo();
  2051. m_glctx.resize(_width, _height, _flags);
  2052. uint32_t msaa = (_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  2053. msaa = bx::uint32_min(m_maxMsaa, msaa == 0 ? 0 : 1<<msaa);
  2054. createMsaaFbo(_width, _height, msaa);
  2055. }
  2056. }
  2057. m_flip = true;
  2058. }
  2059. void invalidateCache()
  2060. {
  2061. if (m_vaoSupport)
  2062. {
  2063. m_vaoStateCache.invalidate();
  2064. }
  2065. if ( (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2066. && m_samplerObjectSupport)
  2067. {
  2068. m_samplerStateCache.invalidate();
  2069. }
  2070. }
  2071. void setSamplerState(uint32_t _stage, uint32_t _numMips, uint32_t _flags)
  2072. {
  2073. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  2074. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  2075. {
  2076. if (0 == (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) )
  2077. {
  2078. _flags &= ~BGFX_TEXTURE_RESERVED_MASK;
  2079. _flags &= BGFX_TEXTURE_SAMPLER_BITS_MASK;
  2080. _flags |= _numMips<<BGFX_TEXTURE_RESERVED_SHIFT;
  2081. GLuint sampler = m_samplerStateCache.find(_flags);
  2082. if (UINT32_MAX == sampler)
  2083. {
  2084. sampler = m_samplerStateCache.add(_flags);
  2085. GL_CHECK(glSamplerParameteri(sampler
  2086. , GL_TEXTURE_WRAP_S
  2087. , s_textureAddress[(_flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]
  2088. ) );
  2089. GL_CHECK(glSamplerParameteri(sampler
  2090. , GL_TEXTURE_WRAP_T
  2091. , s_textureAddress[(_flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]
  2092. ) );
  2093. GL_CHECK(glSamplerParameteri(sampler
  2094. , GL_TEXTURE_WRAP_R
  2095. , s_textureAddress[(_flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]
  2096. ) );
  2097. GLenum minFilter;
  2098. GLenum magFilter;
  2099. getFilters(_flags, 1 < _numMips, magFilter, minFilter);
  2100. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, magFilter) );
  2101. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, minFilter) );
  2102. if (0 != (_flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  2103. && 0.0f < m_maxAnisotropy)
  2104. {
  2105. GL_CHECK(glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, m_maxAnisotropy) );
  2106. }
  2107. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  2108. || m_shadowSamplersSupport)
  2109. {
  2110. const uint32_t cmpFunc = (_flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  2111. if (0 == cmpFunc)
  2112. {
  2113. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  2114. }
  2115. else
  2116. {
  2117. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  2118. GL_CHECK(glSamplerParameteri(sampler, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  2119. }
  2120. }
  2121. }
  2122. GL_CHECK(glBindSampler(_stage, sampler) );
  2123. }
  2124. else
  2125. {
  2126. GL_CHECK(glBindSampler(_stage, 0) );
  2127. }
  2128. }
  2129. }
  2130. void ovrPostReset()
  2131. {
  2132. #if BGFX_CONFIG_USE_OVR
  2133. if (m_resolution.m_flags & (BGFX_RESET_HMD|BGFX_RESET_HMD_DEBUG) )
  2134. {
  2135. ovrGLConfig config;
  2136. config.OGL.Header.API = ovrRenderAPI_OpenGL;
  2137. # if OVR_VERSION > OVR_VERSION_043
  2138. config.OGL.Header.BackBufferSize.w = m_resolution.m_width;
  2139. config.OGL.Header.BackBufferSize.h = m_resolution.m_height;
  2140. # else
  2141. config.OGL.Header.RTSize.w = m_resolution.m_width;
  2142. config.OGL.Header.RTSize.h = m_resolution.m_height;
  2143. # endif // OVR_VERSION > OVR_VERSION_043
  2144. config.OGL.Header.Multisample = 0;
  2145. config.OGL.Window = (HWND)g_platformData.nwh;
  2146. config.OGL.DC = GetDC(config.OGL.Window);
  2147. if (m_ovr.postReset(g_platformData.nwh, &config.Config, !!(m_resolution.m_flags & BGFX_RESET_HMD_DEBUG) ) )
  2148. {
  2149. uint32_t size = sizeof(uint32_t) + sizeof(TextureCreate);
  2150. const Memory* mem = alloc(size);
  2151. bx::StaticMemoryBlockWriter writer(mem->data, mem->size);
  2152. uint32_t magic = BGFX_CHUNK_MAGIC_TEX;
  2153. bx::write(&writer, magic);
  2154. TextureCreate tc;
  2155. tc.m_flags = BGFX_TEXTURE_RT|(((m_resolution.m_flags & BGFX_RESET_MSAA_MASK) >> BGFX_RESET_MSAA_SHIFT) << BGFX_TEXTURE_RT_MSAA_SHIFT);;
  2156. tc.m_width = m_ovr.m_rtSize.w;
  2157. tc.m_height = m_ovr.m_rtSize.h;
  2158. tc.m_sides = 0;
  2159. tc.m_depth = 0;
  2160. tc.m_numMips = 1;
  2161. tc.m_format = uint8_t(bgfx::TextureFormat::BGRA8);
  2162. tc.m_cubeMap = false;
  2163. tc.m_mem = NULL;
  2164. bx::write(&writer, tc);
  2165. m_ovrRT.create(mem, tc.m_flags, 0);
  2166. release(mem);
  2167. m_ovrFbo = m_msaaBackBufferFbo;
  2168. GL_CHECK(glGenFramebuffers(1, &m_msaaBackBufferFbo) );
  2169. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  2170. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  2171. , GL_COLOR_ATTACHMENT0
  2172. , GL_TEXTURE_2D
  2173. , m_ovrRT.m_id
  2174. , 0
  2175. ) );
  2176. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_ovrFbo) );
  2177. ovrGLTexture texture;
  2178. texture.OGL.Header.API = ovrRenderAPI_OpenGL;
  2179. texture.OGL.Header.TextureSize = m_ovr.m_rtSize;
  2180. texture.OGL.TexId = m_ovrRT.m_id;
  2181. m_ovr.postReset(texture.Texture);
  2182. }
  2183. }
  2184. #endif // BGFX_CONFIG_USE_OVR
  2185. }
  2186. void ovrPreReset()
  2187. {
  2188. #if BGFX_CONFIG_USE_OVR
  2189. m_ovr.preReset();
  2190. if (m_ovr.isEnabled() )
  2191. {
  2192. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, 0) );
  2193. GL_CHECK(glDeleteFramebuffers(1, &m_msaaBackBufferFbo) );
  2194. m_msaaBackBufferFbo = m_ovrFbo;
  2195. m_ovrFbo = 0;
  2196. m_ovrRT.destroy();
  2197. }
  2198. #endif // BGFX_CONFIG_USE_OVR
  2199. }
  2200. void updateCapture()
  2201. {
  2202. if (m_resolution.m_flags&BGFX_RESET_CAPTURE)
  2203. {
  2204. m_captureSize = m_resolution.m_width*m_resolution.m_height*4;
  2205. m_capture = BX_REALLOC(g_allocator, m_capture, m_captureSize);
  2206. g_callback->captureBegin(m_resolution.m_width, m_resolution.m_height, m_resolution.m_width*4, TextureFormat::BGRA8, true);
  2207. }
  2208. else
  2209. {
  2210. captureFinish();
  2211. }
  2212. }
  2213. void capture()
  2214. {
  2215. if (NULL != m_capture)
  2216. {
  2217. GL_CHECK(glReadPixels(0
  2218. , 0
  2219. , m_resolution.m_width
  2220. , m_resolution.m_height
  2221. , m_readPixelsFmt
  2222. , GL_UNSIGNED_BYTE
  2223. , m_capture
  2224. ) );
  2225. g_callback->captureFrame(m_capture, m_captureSize);
  2226. }
  2227. }
  2228. void captureFinish()
  2229. {
  2230. if (NULL != m_capture)
  2231. {
  2232. g_callback->captureEnd();
  2233. BX_FREE(g_allocator, m_capture);
  2234. m_capture = NULL;
  2235. m_captureSize = 0;
  2236. }
  2237. }
  2238. bool programFetchFromCache(GLuint programId, uint64_t _id)
  2239. {
  2240. _id ^= m_hash;
  2241. bool cached = false;
  2242. if (m_programBinarySupport)
  2243. {
  2244. uint32_t length = g_callback->cacheReadSize(_id);
  2245. cached = length > 0;
  2246. if (cached)
  2247. {
  2248. void* data = BX_ALLOC(g_allocator, length);
  2249. if (g_callback->cacheRead(_id, data, length) )
  2250. {
  2251. bx::MemoryReader reader(data, length);
  2252. GLenum format;
  2253. bx::read(&reader, format);
  2254. GL_CHECK(glProgramBinary(programId, format, reader.getDataPtr(), (GLsizei)reader.remaining() ) );
  2255. }
  2256. BX_FREE(g_allocator, data);
  2257. }
  2258. #if BGFX_CONFIG_RENDERER_OPENGL
  2259. GL_CHECK(glProgramParameteri(programId, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE) );
  2260. #endif // BGFX_CONFIG_RENDERER_OPENGL
  2261. }
  2262. return cached;
  2263. }
  2264. void programCache(GLuint programId, uint64_t _id)
  2265. {
  2266. _id ^= m_hash;
  2267. if (m_programBinarySupport)
  2268. {
  2269. GLint programLength;
  2270. GLenum format;
  2271. GL_CHECK(glGetProgramiv(programId, GL_PROGRAM_BINARY_LENGTH, &programLength) );
  2272. if (0 < programLength)
  2273. {
  2274. uint32_t length = programLength + 4;
  2275. uint8_t* data = (uint8_t*)BX_ALLOC(g_allocator, length);
  2276. GL_CHECK(glGetProgramBinary(programId, programLength, NULL, &format, &data[4]) );
  2277. *(uint32_t*)data = format;
  2278. g_callback->cacheWrite(_id, data, length);
  2279. BX_FREE(g_allocator, data);
  2280. }
  2281. }
  2282. }
  2283. void commit(ConstantBuffer& _constantBuffer)
  2284. {
  2285. _constantBuffer.reset();
  2286. for (;;)
  2287. {
  2288. uint32_t opcode = _constantBuffer.read();
  2289. if (UniformType::End == opcode)
  2290. {
  2291. break;
  2292. }
  2293. UniformType::Enum type;
  2294. uint16_t ignore;
  2295. uint16_t num;
  2296. uint16_t copy;
  2297. ConstantBuffer::decodeOpcode(opcode, type, ignore, num, copy);
  2298. const char* data;
  2299. if (copy)
  2300. {
  2301. data = _constantBuffer.read(g_uniformTypeSize[type]*num);
  2302. }
  2303. else
  2304. {
  2305. UniformHandle handle;
  2306. memcpy(&handle, _constantBuffer.read(sizeof(UniformHandle) ), sizeof(UniformHandle) );
  2307. data = (const char*)m_uniforms[handle.idx];
  2308. }
  2309. uint32_t loc = _constantBuffer.read();
  2310. #define CASE_IMPLEMENT_UNIFORM(_uniform, _glsuffix, _dxsuffix, _type) \
  2311. case UniformType::_uniform: \
  2312. { \
  2313. _type* value = (_type*)data; \
  2314. GL_CHECK(glUniform##_glsuffix(loc, num, value) ); \
  2315. } \
  2316. break;
  2317. #define CASE_IMPLEMENT_UNIFORM_T(_uniform, _glsuffix, _dxsuffix, _type) \
  2318. case UniformType::_uniform: \
  2319. { \
  2320. _type* value = (_type*)data; \
  2321. GL_CHECK(glUniform##_glsuffix(loc, num, GL_FALSE, value) ); \
  2322. } \
  2323. break;
  2324. switch (type)
  2325. {
  2326. // case ConstantType::Int1:
  2327. // {
  2328. // int* value = (int*)data;
  2329. // BX_TRACE("Int1 sampler %d, loc %d (num %d, copy %d)", *value, loc, num, copy);
  2330. // GL_CHECK(glUniform1iv(loc, num, value) );
  2331. // }
  2332. // break;
  2333. CASE_IMPLEMENT_UNIFORM(Int1, 1iv, I, int);
  2334. CASE_IMPLEMENT_UNIFORM(Vec4, 4fv, F, float);
  2335. CASE_IMPLEMENT_UNIFORM_T(Mat3, Matrix3fv, F, float);
  2336. CASE_IMPLEMENT_UNIFORM_T(Mat4, Matrix4fv, F, float);
  2337. case UniformType::End:
  2338. break;
  2339. default:
  2340. BX_TRACE("%4d: INVALID 0x%08x, t %d, l %d, n %d, c %d", _constantBuffer.getPos(), opcode, type, loc, num, copy);
  2341. break;
  2342. }
  2343. #undef CASE_IMPLEMENT_UNIFORM
  2344. #undef CASE_IMPLEMENT_UNIFORM_T
  2345. }
  2346. }
  2347. void clearQuad(ClearQuad& _clearQuad, const Rect& _rect, const Clear& _clear, uint32_t _height, const float _palette[][4])
  2348. {
  2349. uint32_t numMrt = 1;
  2350. FrameBufferHandle fbh = m_fbh;
  2351. if (isValid(fbh) )
  2352. {
  2353. const FrameBufferGL& fb = m_frameBuffers[fbh.idx];
  2354. numMrt = bx::uint32_max(1, fb.m_num);
  2355. }
  2356. if (1 == numMrt)
  2357. {
  2358. GLuint flags = 0;
  2359. if (BGFX_CLEAR_COLOR & _clear.m_flags)
  2360. {
  2361. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2362. {
  2363. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE-1, _clear.m_index[0]);
  2364. const float* rgba = _palette[index];
  2365. const float rr = rgba[0];
  2366. const float gg = rgba[1];
  2367. const float bb = rgba[2];
  2368. const float aa = rgba[3];
  2369. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2370. }
  2371. else
  2372. {
  2373. float rr = _clear.m_index[0]*1.0f/255.0f;
  2374. float gg = _clear.m_index[1]*1.0f/255.0f;
  2375. float bb = _clear.m_index[2]*1.0f/255.0f;
  2376. float aa = _clear.m_index[3]*1.0f/255.0f;
  2377. GL_CHECK(glClearColor(rr, gg, bb, aa) );
  2378. }
  2379. flags |= GL_COLOR_BUFFER_BIT;
  2380. GL_CHECK(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE) );
  2381. }
  2382. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2383. {
  2384. flags |= GL_DEPTH_BUFFER_BIT;
  2385. GL_CHECK(glClearDepth(_clear.m_depth) );
  2386. GL_CHECK(glDepthMask(GL_TRUE) );
  2387. }
  2388. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2389. {
  2390. flags |= GL_STENCIL_BUFFER_BIT;
  2391. GL_CHECK(glClearStencil(_clear.m_stencil) );
  2392. }
  2393. if (0 != flags)
  2394. {
  2395. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  2396. GL_CHECK(glScissor(_rect.m_x, _height-_rect.m_height-_rect.m_y, _rect.m_width, _rect.m_height) );
  2397. GL_CHECK(glClear(flags) );
  2398. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2399. }
  2400. }
  2401. else
  2402. {
  2403. const GLuint defaultVao = m_vao;
  2404. if (0 != defaultVao)
  2405. {
  2406. GL_CHECK(glBindVertexArray(defaultVao) );
  2407. }
  2408. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  2409. GL_CHECK(glDisable(GL_CULL_FACE) );
  2410. GL_CHECK(glDisable(GL_BLEND) );
  2411. GLboolean colorMask = !!(BGFX_CLEAR_COLOR & _clear.m_flags);
  2412. GL_CHECK(glColorMask(colorMask, colorMask, colorMask, colorMask) );
  2413. if (BGFX_CLEAR_DEPTH & _clear.m_flags)
  2414. {
  2415. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  2416. GL_CHECK(glDepthFunc(GL_ALWAYS) );
  2417. GL_CHECK(glDepthMask(GL_TRUE) );
  2418. }
  2419. else
  2420. {
  2421. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  2422. }
  2423. if (BGFX_CLEAR_STENCIL & _clear.m_flags)
  2424. {
  2425. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  2426. GL_CHECK(glStencilFuncSeparate(GL_FRONT_AND_BACK, GL_ALWAYS, _clear.m_stencil, 0xff) );
  2427. GL_CHECK(glStencilOpSeparate(GL_FRONT_AND_BACK, GL_REPLACE, GL_REPLACE, GL_REPLACE) );
  2428. }
  2429. else
  2430. {
  2431. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  2432. }
  2433. VertexBufferGL& vb = m_vertexBuffers[_clearQuad.m_vb->handle.idx];
  2434. VertexDecl& vertexDecl = m_vertexDecls[_clearQuad.m_vb->decl.idx];
  2435. {
  2436. struct Vertex
  2437. {
  2438. float m_x;
  2439. float m_y;
  2440. float m_z;
  2441. };
  2442. Vertex* vertex = (Vertex*)_clearQuad.m_vb->data;
  2443. BX_CHECK(vertexDecl.m_stride == sizeof(Vertex), "Stride/Vertex mismatch (stride %d, sizeof(Vertex) %d)", vertexDecl.m_stride, sizeof(Vertex) );
  2444. const float depth = _clear.m_depth;
  2445. vertex->m_x = -1.0f;
  2446. vertex->m_y = -1.0f;
  2447. vertex->m_z = depth;
  2448. vertex++;
  2449. vertex->m_x = 1.0f;
  2450. vertex->m_y = -1.0f;
  2451. vertex->m_z = depth;
  2452. vertex++;
  2453. vertex->m_x = -1.0f;
  2454. vertex->m_y = 1.0f;
  2455. vertex->m_z = depth;
  2456. vertex++;
  2457. vertex->m_x = 1.0f;
  2458. vertex->m_y = 1.0f;
  2459. vertex->m_z = depth;
  2460. }
  2461. vb.update(0, 4*_clearQuad.m_decl.m_stride, _clearQuad.m_vb->data);
  2462. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  2463. ProgramGL& program = m_program[_clearQuad.m_program[numMrt-1].idx];
  2464. GL_CHECK(glUseProgram(program.m_id) );
  2465. program.bindAttributes(vertexDecl, 0);
  2466. if (BGFX_CLEAR_COLOR_USE_PALETTE & _clear.m_flags)
  2467. {
  2468. float mrtClear[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS][4];
  2469. for (uint32_t ii = 0; ii < numMrt; ++ii)
  2470. {
  2471. uint8_t index = (uint8_t)bx::uint32_min(BGFX_CONFIG_MAX_CLEAR_COLOR_PALETTE-1, _clear.m_index[ii]);
  2472. memcpy(mrtClear[ii], _palette[index], 16);
  2473. }
  2474. GL_CHECK(glUniform4fv(0, numMrt, mrtClear[0]) );
  2475. }
  2476. else
  2477. {
  2478. float rgba[4] =
  2479. {
  2480. _clear.m_index[0]*1.0f/255.0f,
  2481. _clear.m_index[1]*1.0f/255.0f,
  2482. _clear.m_index[2]*1.0f/255.0f,
  2483. _clear.m_index[3]*1.0f/255.0f,
  2484. };
  2485. GL_CHECK(glUniform4fv(0, 1, rgba) );
  2486. }
  2487. GL_CHECK(glDrawArrays(GL_TRIANGLE_STRIP
  2488. , 0
  2489. , 4
  2490. ) );
  2491. }
  2492. }
  2493. void* m_renderdocdll;
  2494. uint16_t m_numWindows;
  2495. FrameBufferHandle m_windows[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2496. IndexBufferGL m_indexBuffers[BGFX_CONFIG_MAX_INDEX_BUFFERS];
  2497. VertexBufferGL m_vertexBuffers[BGFX_CONFIG_MAX_VERTEX_BUFFERS];
  2498. ShaderGL m_shaders[BGFX_CONFIG_MAX_SHADERS];
  2499. ProgramGL m_program[BGFX_CONFIG_MAX_PROGRAMS];
  2500. TextureGL m_textures[BGFX_CONFIG_MAX_TEXTURES];
  2501. VertexDecl m_vertexDecls[BGFX_CONFIG_MAX_VERTEX_DECLS];
  2502. FrameBufferGL m_frameBuffers[BGFX_CONFIG_MAX_FRAME_BUFFERS];
  2503. UniformRegistry m_uniformReg;
  2504. void* m_uniforms[BGFX_CONFIG_MAX_UNIFORMS];
  2505. QueriesGL m_queries;
  2506. VaoStateCache m_vaoStateCache;
  2507. SamplerStateCache m_samplerStateCache;
  2508. TextVideoMem m_textVideoMem;
  2509. bool m_rtMsaa;
  2510. FrameBufferHandle m_fbh;
  2511. uint16_t m_fbDiscard;
  2512. Resolution m_resolution;
  2513. void* m_capture;
  2514. uint32_t m_captureSize;
  2515. float m_maxAnisotropy;
  2516. float m_maxAnisotropyDefault;
  2517. int32_t m_maxMsaa;
  2518. GLuint m_vao;
  2519. bool m_vaoSupport;
  2520. bool m_samplerObjectSupport;
  2521. bool m_shadowSamplersSupport;
  2522. bool m_programBinarySupport;
  2523. bool m_textureSwizzleSupport;
  2524. bool m_depthTextureSupport;
  2525. bool m_timerQuerySupport;
  2526. bool m_flip;
  2527. uint64_t m_hash;
  2528. GLenum m_readPixelsFmt;
  2529. GLuint m_backBufferFbo;
  2530. GLuint m_msaaBackBufferFbo;
  2531. GLuint m_msaaBackBufferRbos[2];
  2532. GlContext m_glctx;
  2533. const char* m_vendor;
  2534. const char* m_renderer;
  2535. const char* m_version;
  2536. const char* m_glslVersion;
  2537. OVR m_ovr;
  2538. TextureGL m_ovrRT;
  2539. GLint m_ovrFbo;
  2540. };
  2541. RendererContextGL* s_renderGL;
  2542. RendererContextI* rendererCreate()
  2543. {
  2544. s_renderGL = BX_NEW(g_allocator, RendererContextGL);
  2545. s_renderGL->init();
  2546. return s_renderGL;
  2547. }
  2548. void rendererDestroy()
  2549. {
  2550. s_renderGL->shutdown();
  2551. BX_DELETE(g_allocator, s_renderGL);
  2552. s_renderGL = NULL;
  2553. }
  2554. const char* glslTypeName(GLuint _type)
  2555. {
  2556. #define GLSL_TYPE(_ty) case _ty: return #_ty
  2557. switch (_type)
  2558. {
  2559. GLSL_TYPE(GL_INT);
  2560. GLSL_TYPE(GL_INT_VEC2);
  2561. GLSL_TYPE(GL_INT_VEC3);
  2562. GLSL_TYPE(GL_INT_VEC4);
  2563. GLSL_TYPE(GL_UNSIGNED_INT);
  2564. GLSL_TYPE(GL_UNSIGNED_INT_VEC2);
  2565. GLSL_TYPE(GL_UNSIGNED_INT_VEC3);
  2566. GLSL_TYPE(GL_UNSIGNED_INT_VEC4);
  2567. GLSL_TYPE(GL_FLOAT);
  2568. GLSL_TYPE(GL_FLOAT_VEC2);
  2569. GLSL_TYPE(GL_FLOAT_VEC3);
  2570. GLSL_TYPE(GL_FLOAT_VEC4);
  2571. GLSL_TYPE(GL_FLOAT_MAT2);
  2572. GLSL_TYPE(GL_FLOAT_MAT3);
  2573. GLSL_TYPE(GL_FLOAT_MAT4);
  2574. GLSL_TYPE(GL_SAMPLER_2D);
  2575. GLSL_TYPE(GL_INT_SAMPLER_2D);
  2576. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_2D);
  2577. GLSL_TYPE(GL_SAMPLER_3D);
  2578. GLSL_TYPE(GL_INT_SAMPLER_3D);
  2579. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_3D);
  2580. GLSL_TYPE(GL_SAMPLER_CUBE);
  2581. GLSL_TYPE(GL_INT_SAMPLER_CUBE);
  2582. GLSL_TYPE(GL_UNSIGNED_INT_SAMPLER_CUBE);
  2583. GLSL_TYPE(GL_SAMPLER_2D_SHADOW);
  2584. GLSL_TYPE(GL_IMAGE_1D);
  2585. GLSL_TYPE(GL_INT_IMAGE_1D);
  2586. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_1D);
  2587. GLSL_TYPE(GL_IMAGE_2D);
  2588. GLSL_TYPE(GL_INT_IMAGE_2D);
  2589. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_2D);
  2590. GLSL_TYPE(GL_IMAGE_3D);
  2591. GLSL_TYPE(GL_INT_IMAGE_3D);
  2592. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_3D);
  2593. GLSL_TYPE(GL_IMAGE_CUBE);
  2594. GLSL_TYPE(GL_INT_IMAGE_CUBE);
  2595. GLSL_TYPE(GL_UNSIGNED_INT_IMAGE_CUBE);
  2596. }
  2597. #undef GLSL_TYPE
  2598. BX_CHECK(false, "Unknown GLSL type? %x", _type);
  2599. return "UNKNOWN GLSL TYPE!";
  2600. }
  2601. const char* glEnumName(GLenum _enum)
  2602. {
  2603. #define GLENUM(_ty) case _ty: return #_ty
  2604. switch (_enum)
  2605. {
  2606. GLENUM(GL_TEXTURE);
  2607. GLENUM(GL_RENDERBUFFER);
  2608. GLENUM(GL_INVALID_ENUM);
  2609. GLENUM(GL_INVALID_FRAMEBUFFER_OPERATION);
  2610. GLENUM(GL_INVALID_VALUE);
  2611. GLENUM(GL_INVALID_OPERATION);
  2612. GLENUM(GL_OUT_OF_MEMORY);
  2613. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
  2614. GLENUM(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
  2615. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER);
  2616. // GLENUM(GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER);
  2617. GLENUM(GL_FRAMEBUFFER_UNSUPPORTED);
  2618. }
  2619. #undef GLENUM
  2620. BX_WARN(false, "Unknown enum? %x", _enum);
  2621. return "<GLenum?>";
  2622. }
  2623. UniformType::Enum convertGlType(GLenum _type)
  2624. {
  2625. switch (_type)
  2626. {
  2627. case GL_INT:
  2628. case GL_UNSIGNED_INT:
  2629. return UniformType::Int1;
  2630. case GL_FLOAT:
  2631. case GL_FLOAT_VEC2:
  2632. case GL_FLOAT_VEC3:
  2633. case GL_FLOAT_VEC4:
  2634. return UniformType::Vec4;
  2635. case GL_FLOAT_MAT2:
  2636. break;
  2637. case GL_FLOAT_MAT3:
  2638. return UniformType::Mat3;
  2639. case GL_FLOAT_MAT4:
  2640. return UniformType::Mat4;
  2641. case GL_SAMPLER_2D:
  2642. case GL_INT_SAMPLER_2D:
  2643. case GL_UNSIGNED_INT_SAMPLER_2D:
  2644. case GL_SAMPLER_3D:
  2645. case GL_INT_SAMPLER_3D:
  2646. case GL_UNSIGNED_INT_SAMPLER_3D:
  2647. case GL_SAMPLER_CUBE:
  2648. case GL_INT_SAMPLER_CUBE:
  2649. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  2650. case GL_SAMPLER_2D_SHADOW:
  2651. case GL_IMAGE_1D:
  2652. case GL_INT_IMAGE_1D:
  2653. case GL_UNSIGNED_INT_IMAGE_1D:
  2654. case GL_IMAGE_2D:
  2655. case GL_INT_IMAGE_2D:
  2656. case GL_UNSIGNED_INT_IMAGE_2D:
  2657. case GL_IMAGE_3D:
  2658. case GL_INT_IMAGE_3D:
  2659. case GL_UNSIGNED_INT_IMAGE_3D:
  2660. case GL_IMAGE_CUBE:
  2661. case GL_INT_IMAGE_CUBE:
  2662. case GL_UNSIGNED_INT_IMAGE_CUBE:
  2663. return UniformType::Int1;
  2664. };
  2665. BX_CHECK(false, "Unrecognized GL type 0x%04x.", _type);
  2666. return UniformType::End;
  2667. }
  2668. void ProgramGL::create(const ShaderGL& _vsh, const ShaderGL& _fsh)
  2669. {
  2670. m_id = glCreateProgram();
  2671. BX_TRACE("Program create: GL%d: GL%d, GL%d", m_id, _vsh.m_id, _fsh.m_id);
  2672. const uint64_t id = (uint64_t(_vsh.m_hash)<<32) | _fsh.m_hash;
  2673. const bool cached = s_renderGL->programFetchFromCache(m_id, id);
  2674. if (!cached)
  2675. {
  2676. GLint linked = 0;
  2677. if (0 != _vsh.m_id)
  2678. {
  2679. GL_CHECK(glAttachShader(m_id, _vsh.m_id) );
  2680. if (0 != _fsh.m_id)
  2681. {
  2682. GL_CHECK(glAttachShader(m_id, _fsh.m_id) );
  2683. }
  2684. GL_CHECK(glLinkProgram(m_id) );
  2685. GL_CHECK(glGetProgramiv(m_id, GL_LINK_STATUS, &linked) );
  2686. if (0 == linked)
  2687. {
  2688. char log[1024];
  2689. GL_CHECK(glGetProgramInfoLog(m_id, sizeof(log), NULL, log) );
  2690. BX_TRACE("%d: %s", linked, log);
  2691. }
  2692. }
  2693. if (0 == linked)
  2694. {
  2695. BX_WARN(0 != _vsh.m_id, "Invalid vertex/compute shader.");
  2696. GL_CHECK(glDeleteProgram(m_id) );
  2697. m_used[0] = Attrib::Count;
  2698. m_id = 0;
  2699. return;
  2700. }
  2701. s_renderGL->programCache(m_id, id);
  2702. }
  2703. init();
  2704. if (!cached)
  2705. {
  2706. // Must be after init, otherwise init might fail to lookup shader
  2707. // info (NVIDIA Tegra 3 OpenGL ES 2.0 14.01003).
  2708. GL_CHECK(glDetachShader(m_id, _vsh.m_id) );
  2709. if (0 != _fsh.m_id)
  2710. {
  2711. GL_CHECK(glDetachShader(m_id, _fsh.m_id) );
  2712. }
  2713. }
  2714. }
  2715. void ProgramGL::destroy()
  2716. {
  2717. if (NULL != m_constantBuffer)
  2718. {
  2719. ConstantBuffer::destroy(m_constantBuffer);
  2720. m_constantBuffer = NULL;
  2721. }
  2722. m_numPredefined = 0;
  2723. if (0 != m_id)
  2724. {
  2725. GL_CHECK(glUseProgram(0) );
  2726. GL_CHECK(glDeleteProgram(m_id) );
  2727. m_id = 0;
  2728. }
  2729. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  2730. }
  2731. void ProgramGL::init()
  2732. {
  2733. GLint activeAttribs = 0;
  2734. GLint activeUniforms = 0;
  2735. GLint activeBuffers = 0;
  2736. #if BGFX_CONFIG_RENDERER_OPENGL >= 31
  2737. GL_CHECK(glBindFragDataLocation(m_id, 0, "bgfx_FragColor") );
  2738. #endif // BGFX_CONFIG_RENDERER_OPENGL >= 31
  2739. if (s_extension[Extension::ARB_program_interface_query].m_supported
  2740. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  2741. {
  2742. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &activeAttribs ) );
  2743. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_UNIFORM, GL_ACTIVE_RESOURCES, &activeUniforms) );
  2744. GL_CHECK(glGetProgramInterfaceiv(m_id, GL_BUFFER_VARIABLE, GL_ACTIVE_RESOURCES, &activeBuffers ) );
  2745. }
  2746. else
  2747. {
  2748. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTES, &activeAttribs ) );
  2749. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORMS, &activeUniforms) );
  2750. }
  2751. GLint max0, max1;
  2752. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &max0) );
  2753. GL_CHECK(glGetProgramiv(m_id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &max1) );
  2754. uint32_t maxLength = bx::uint32_max(max0, max1);
  2755. char* name = (char*)alloca(maxLength + 1);
  2756. BX_TRACE("Program %d", m_id);
  2757. BX_TRACE("Attributes (%d):", activeAttribs);
  2758. for (int32_t ii = 0; ii < activeAttribs; ++ii)
  2759. {
  2760. GLint size;
  2761. GLenum type;
  2762. GL_CHECK(glGetActiveAttrib(m_id, ii, maxLength + 1, NULL, &size, &type, name) );
  2763. BX_TRACE("\t%s %s is at location %d"
  2764. , glslTypeName(type)
  2765. , name
  2766. , glGetAttribLocation(m_id, name)
  2767. );
  2768. }
  2769. m_numPredefined = 0;
  2770. m_numSamplers = 0;
  2771. const bool piqSupported = s_extension[Extension::ARB_program_interface_query].m_supported;
  2772. BX_TRACE("Uniforms (%d):", activeUniforms);
  2773. for (int32_t ii = 0; ii < activeUniforms; ++ii)
  2774. {
  2775. struct VariableInfo
  2776. {
  2777. GLenum type;
  2778. GLint loc;
  2779. GLint num;
  2780. };
  2781. VariableInfo vi;
  2782. GLenum props[] ={ GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE };
  2783. GLenum gltype;
  2784. GLint num;
  2785. GLint loc;
  2786. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  2787. || piqSupported)
  2788. {
  2789. GL_CHECK(glGetProgramResourceiv(m_id
  2790. , GL_UNIFORM
  2791. , ii
  2792. , BX_COUNTOF(props)
  2793. , props
  2794. , BX_COUNTOF(props)
  2795. , NULL
  2796. , (GLint*)&vi
  2797. ) );
  2798. GL_CHECK(glGetProgramResourceName(m_id
  2799. , GL_UNIFORM
  2800. , ii
  2801. , maxLength + 1
  2802. , NULL
  2803. , name
  2804. ) );
  2805. gltype = vi.type;
  2806. loc = vi.loc;
  2807. num = vi.num;
  2808. }
  2809. else
  2810. {
  2811. GL_CHECK(glGetActiveUniform(m_id, ii, maxLength + 1, NULL, &num, &gltype, name) );
  2812. loc = glGetUniformLocation(m_id, name);
  2813. }
  2814. num = bx::uint32_max(num, 1);
  2815. int offset = 0;
  2816. char* array = strchr(name, '[');
  2817. if (NULL != array)
  2818. {
  2819. BX_TRACE("--- %s", name);
  2820. *array = '\0';
  2821. array++;
  2822. char* end = strchr(array, ']');
  2823. if (NULL != end)
  2824. { // Some devices (Amazon Fire) might not return terminating brace.
  2825. *end = '\0';
  2826. offset = atoi(array);
  2827. }
  2828. }
  2829. switch (gltype)
  2830. {
  2831. case GL_SAMPLER_2D:
  2832. case GL_INT_SAMPLER_2D:
  2833. case GL_UNSIGNED_INT_SAMPLER_2D:
  2834. case GL_SAMPLER_3D:
  2835. case GL_INT_SAMPLER_3D:
  2836. case GL_UNSIGNED_INT_SAMPLER_3D:
  2837. case GL_SAMPLER_CUBE:
  2838. case GL_INT_SAMPLER_CUBE:
  2839. case GL_UNSIGNED_INT_SAMPLER_CUBE:
  2840. case GL_SAMPLER_2D_SHADOW:
  2841. case GL_IMAGE_1D:
  2842. case GL_INT_IMAGE_1D:
  2843. case GL_UNSIGNED_INT_IMAGE_1D:
  2844. case GL_IMAGE_2D:
  2845. case GL_INT_IMAGE_2D:
  2846. case GL_UNSIGNED_INT_IMAGE_2D:
  2847. case GL_IMAGE_3D:
  2848. case GL_INT_IMAGE_3D:
  2849. case GL_UNSIGNED_INT_IMAGE_3D:
  2850. case GL_IMAGE_CUBE:
  2851. case GL_INT_IMAGE_CUBE:
  2852. case GL_UNSIGNED_INT_IMAGE_CUBE:
  2853. BX_TRACE("Sampler #%d at location %d.", m_numSamplers, loc);
  2854. m_sampler[m_numSamplers] = loc;
  2855. m_numSamplers++;
  2856. break;
  2857. default:
  2858. break;
  2859. }
  2860. PredefinedUniform::Enum predefined = nameToPredefinedUniformEnum(name);
  2861. if (PredefinedUniform::Count != predefined)
  2862. {
  2863. m_predefined[m_numPredefined].m_loc = loc;
  2864. m_predefined[m_numPredefined].m_count = uint16_t(num);
  2865. m_predefined[m_numPredefined].m_type = uint8_t(predefined);
  2866. m_numPredefined++;
  2867. }
  2868. else
  2869. {
  2870. const UniformInfo* info = s_renderGL->m_uniformReg.find(name);
  2871. if (NULL != info)
  2872. {
  2873. if (NULL == m_constantBuffer)
  2874. {
  2875. m_constantBuffer = ConstantBuffer::create(1024);
  2876. }
  2877. UniformType::Enum type = convertGlType(gltype);
  2878. m_constantBuffer->writeUniformHandle(type, 0, info->m_handle, uint16_t(num) );
  2879. m_constantBuffer->write(loc);
  2880. BX_TRACE("store %s %d", name, info->m_handle);
  2881. }
  2882. }
  2883. BX_TRACE("\tuniform %s %s%s is at location %d, size %d, offset %d"
  2884. , glslTypeName(gltype)
  2885. , name
  2886. , PredefinedUniform::Count != predefined ? "*" : ""
  2887. , loc
  2888. , num
  2889. , offset
  2890. );
  2891. BX_UNUSED(offset);
  2892. }
  2893. if (NULL != m_constantBuffer)
  2894. {
  2895. m_constantBuffer->finish();
  2896. }
  2897. if (s_extension[Extension::ARB_program_interface_query].m_supported
  2898. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31) )
  2899. {
  2900. struct VariableInfo
  2901. {
  2902. GLenum type;
  2903. };
  2904. VariableInfo vi;
  2905. GLenum props[] = { GL_TYPE };
  2906. BX_TRACE("Buffers (%d):", activeBuffers);
  2907. for (int32_t ii = 0; ii < activeBuffers; ++ii)
  2908. {
  2909. GL_CHECK(glGetProgramResourceiv(m_id
  2910. , GL_BUFFER_VARIABLE
  2911. , ii
  2912. , BX_COUNTOF(props)
  2913. , props
  2914. , BX_COUNTOF(props)
  2915. , NULL
  2916. , (GLint*)&vi
  2917. ) );
  2918. GL_CHECK(glGetProgramResourceName(m_id
  2919. , GL_BUFFER_VARIABLE
  2920. , ii
  2921. , maxLength + 1
  2922. , NULL
  2923. , name
  2924. ) );
  2925. BX_TRACE("\t%s %s at %d"
  2926. , glslTypeName(vi.type)
  2927. , name
  2928. , 0 //vi.loc
  2929. );
  2930. }
  2931. }
  2932. memset(m_attributes, 0xff, sizeof(m_attributes) );
  2933. uint32_t used = 0;
  2934. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  2935. {
  2936. GLint loc = glGetAttribLocation(m_id, s_attribName[ii]);
  2937. if (-1 != loc)
  2938. {
  2939. BX_TRACE("attr %s: %d", s_attribName[ii], loc);
  2940. m_attributes[ii] = loc;
  2941. m_used[used++] = ii;
  2942. }
  2943. }
  2944. m_used[used] = Attrib::Count;
  2945. used = 0;
  2946. for (uint32_t ii = 0; ii < BX_COUNTOF(s_instanceDataName); ++ii)
  2947. {
  2948. GLuint loc = glGetAttribLocation(m_id, s_instanceDataName[ii]);
  2949. if (GLuint(-1) != loc )
  2950. {
  2951. BX_TRACE("instance data %s: %d", s_instanceDataName[ii], loc);
  2952. m_instanceData[used++] = loc;
  2953. }
  2954. }
  2955. m_instanceData[used] = 0xffff;
  2956. }
  2957. void ProgramGL::bindAttributes(const VertexDecl& _vertexDecl, uint32_t _baseVertex) const
  2958. {
  2959. for (uint32_t ii = 0; Attrib::Count != m_used[ii]; ++ii)
  2960. {
  2961. Attrib::Enum attr = Attrib::Enum(m_used[ii]);
  2962. GLint loc = m_attributes[attr];
  2963. uint8_t num;
  2964. AttribType::Enum type;
  2965. bool normalized;
  2966. bool asInt;
  2967. _vertexDecl.decode(attr, num, type, normalized, asInt);
  2968. if (-1 != loc)
  2969. {
  2970. if (0xff != _vertexDecl.m_attributes[attr])
  2971. {
  2972. GL_CHECK(glEnableVertexAttribArray(loc) );
  2973. GL_CHECK(glVertexAttribDivisor(loc, 0) );
  2974. uint32_t baseVertex = _baseVertex*_vertexDecl.m_stride + _vertexDecl.m_offset[attr];
  2975. GL_CHECK(glVertexAttribPointer(loc, num, s_attribType[type], normalized, _vertexDecl.m_stride, (void*)(uintptr_t)baseVertex) );
  2976. }
  2977. else
  2978. {
  2979. GL_CHECK(glDisableVertexAttribArray(loc) );
  2980. }
  2981. }
  2982. }
  2983. }
  2984. void ProgramGL::bindInstanceData(uint32_t _stride, uint32_t _baseVertex) const
  2985. {
  2986. uint32_t baseVertex = _baseVertex;
  2987. for (uint32_t ii = 0; 0xffff != m_instanceData[ii]; ++ii)
  2988. {
  2989. GLint loc = m_instanceData[ii];
  2990. GL_CHECK(glEnableVertexAttribArray(loc) );
  2991. GL_CHECK(glVertexAttribPointer(loc, 4, GL_FLOAT, GL_FALSE, _stride, (void*)(uintptr_t)baseVertex) );
  2992. GL_CHECK(glVertexAttribDivisor(loc, 1) );
  2993. baseVertex += 16;
  2994. }
  2995. }
  2996. void IndexBufferGL::destroy()
  2997. {
  2998. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  2999. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3000. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3001. }
  3002. void VertexBufferGL::destroy()
  3003. {
  3004. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  3005. GL_CHECK(glDeleteBuffers(1, &m_id) );
  3006. m_vcref.invalidate(s_renderGL->m_vaoStateCache);
  3007. }
  3008. static void texImage(GLenum _target, GLint _level, GLint _internalFormat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLenum _format, GLenum _type, const GLvoid* _data)
  3009. {
  3010. if (_target == GL_TEXTURE_3D)
  3011. {
  3012. GL_CHECK(glTexImage3D(_target, _level, _internalFormat, _width, _height, _depth, _border, _format, _type, _data) );
  3013. }
  3014. else
  3015. {
  3016. BX_UNUSED(_depth);
  3017. GL_CHECK(glTexImage2D(_target, _level, _internalFormat, _width, _height, _border, _format, _type, _data) );
  3018. }
  3019. }
  3020. static void texSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLenum _type, const GLvoid* _data)
  3021. {
  3022. if (_target == GL_TEXTURE_3D)
  3023. {
  3024. GL_CHECK(glTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _type, _data) );
  3025. }
  3026. else
  3027. {
  3028. BX_UNUSED(_zoffset, _depth);
  3029. GL_CHECK(glTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _type, _data) );
  3030. }
  3031. }
  3032. static void compressedTexImage(GLenum _target, GLint _level, GLenum _internalformat, GLsizei _width, GLsizei _height, GLsizei _depth, GLint _border, GLsizei _imageSize, const GLvoid* _data)
  3033. {
  3034. if (_target == GL_TEXTURE_3D)
  3035. {
  3036. GL_CHECK(glCompressedTexImage3D(_target, _level, _internalformat, _width, _height, _depth, _border, _imageSize, _data) );
  3037. }
  3038. else
  3039. {
  3040. BX_UNUSED(_depth);
  3041. GL_CHECK(glCompressedTexImage2D(_target, _level, _internalformat, _width, _height, _border, _imageSize, _data) );
  3042. }
  3043. }
  3044. static void compressedTexSubImage(GLenum _target, GLint _level, GLint _xoffset, GLint _yoffset, GLint _zoffset, GLsizei _width, GLsizei _height, GLsizei _depth, GLenum _format, GLsizei _imageSize, const GLvoid* _data)
  3045. {
  3046. if (_target == GL_TEXTURE_3D)
  3047. {
  3048. GL_CHECK(glCompressedTexSubImage3D(_target, _level, _xoffset, _yoffset, _zoffset, _width, _height, _depth, _format, _imageSize, _data) );
  3049. }
  3050. else
  3051. {
  3052. BX_UNUSED(_zoffset, _depth);
  3053. GL_CHECK(glCompressedTexSubImage2D(_target, _level, _xoffset, _yoffset, _width, _height, _format, _imageSize, _data) );
  3054. }
  3055. }
  3056. bool TextureGL::init(GLenum _target, uint32_t _width, uint32_t _height, uint32_t _depth, uint8_t _format, uint8_t _numMips, uint32_t _flags)
  3057. {
  3058. m_target = _target;
  3059. m_numMips = _numMips;
  3060. m_flags = _flags;
  3061. m_width = _width;
  3062. m_height = _height;
  3063. m_depth = _depth;
  3064. m_currentFlags = UINT32_MAX;
  3065. m_requestedFormat = _format;
  3066. m_textureFormat = _format;
  3067. const bool bufferOnly = 0 != (m_flags&BGFX_TEXTURE_RT_BUFFER_ONLY);
  3068. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE );
  3069. if (!bufferOnly)
  3070. {
  3071. GL_CHECK(glGenTextures(1, &m_id) );
  3072. BX_CHECK(0 != m_id, "Failed to generate texture id.");
  3073. GL_CHECK(glBindTexture(_target, m_id) );
  3074. const TextureFormatInfo& tfi = s_textureFormat[_format];
  3075. m_fmt = tfi.m_fmt;
  3076. m_type = tfi.m_type;
  3077. const bool swizzle = true
  3078. && TextureFormat::BGRA8 == m_requestedFormat
  3079. && !s_textureFormat[m_requestedFormat].m_supported
  3080. && !s_renderGL->m_textureSwizzleSupport
  3081. ;
  3082. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3083. const bool convert = false
  3084. || (compressed && m_textureFormat != m_requestedFormat)
  3085. || swizzle
  3086. || !s_textureFormat[m_requestedFormat].m_supported
  3087. ;
  3088. if (convert)
  3089. {
  3090. m_textureFormat = (uint8_t)TextureFormat::RGBA8;
  3091. const TextureFormatInfo& tfiRgba8 = s_textureFormat[TextureFormat::RGBA8];
  3092. m_fmt = tfiRgba8.m_fmt;
  3093. m_type = tfiRgba8.m_type;
  3094. }
  3095. if (computeWrite)
  3096. {
  3097. if (_target == GL_TEXTURE_3D)
  3098. {
  3099. GL_CHECK(glTexStorage3D(_target
  3100. , _numMips
  3101. , s_textureFormat[m_textureFormat].m_internalFmt
  3102. , m_width
  3103. , m_height
  3104. , _depth
  3105. ) );
  3106. }
  3107. else
  3108. {
  3109. GL_CHECK(glTexStorage2D(_target
  3110. , _numMips
  3111. , s_textureFormat[m_textureFormat].m_internalFmt
  3112. , m_width
  3113. , m_height
  3114. ) );
  3115. }
  3116. }
  3117. setSamplerState(_flags);
  3118. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3119. && TextureFormat::BGRA8 == m_requestedFormat
  3120. && !s_textureFormat[m_requestedFormat].m_supported
  3121. && s_renderGL->m_textureSwizzleSupport)
  3122. {
  3123. GLint swizzleMask[] = { GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA };
  3124. GL_CHECK(glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask) );
  3125. }
  3126. }
  3127. const bool renderTarget = 0 != (m_flags&BGFX_TEXTURE_RT_MASK);
  3128. if (renderTarget)
  3129. {
  3130. uint32_t msaaQuality = ( (m_flags&BGFX_TEXTURE_RT_MSAA_MASK)>>BGFX_TEXTURE_RT_MSAA_SHIFT);
  3131. msaaQuality = bx::uint32_satsub(msaaQuality, 1);
  3132. msaaQuality = bx::uint32_min(s_renderGL->m_maxMsaa, msaaQuality == 0 ? 0 : 1<<msaaQuality);
  3133. if (0 != msaaQuality
  3134. || bufferOnly)
  3135. {
  3136. GL_CHECK(glGenRenderbuffers(1, &m_rbo) );
  3137. BX_CHECK(0 != m_rbo, "Failed to generate renderbuffer id.");
  3138. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, m_rbo) );
  3139. if (0 == msaaQuality)
  3140. {
  3141. GL_CHECK(glRenderbufferStorage(GL_RENDERBUFFER
  3142. , s_rboFormat[m_textureFormat]
  3143. , _width
  3144. , _height
  3145. ) );
  3146. }
  3147. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3148. {
  3149. GL_CHECK(glRenderbufferStorageMultisample(GL_RENDERBUFFER
  3150. , msaaQuality
  3151. , s_rboFormat[m_textureFormat]
  3152. , _width
  3153. , _height
  3154. ) );
  3155. }
  3156. GL_CHECK(glBindRenderbuffer(GL_RENDERBUFFER, 0) );
  3157. if (bufferOnly)
  3158. {
  3159. // This is render buffer, there is no sampling, no need
  3160. // to create texture.
  3161. return false;
  3162. }
  3163. }
  3164. }
  3165. return true;
  3166. }
  3167. void TextureGL::create(const Memory* _mem, uint32_t _flags, uint8_t _skip)
  3168. {
  3169. ImageContainer imageContainer;
  3170. if (imageParse(imageContainer, _mem->data, _mem->size) )
  3171. {
  3172. uint8_t numMips = imageContainer.m_numMips;
  3173. const uint8_t startLod = uint8_t(bx::uint32_min(_skip, numMips-1) );
  3174. numMips -= startLod;
  3175. uint32_t textureWidth;
  3176. uint32_t textureHeight;
  3177. uint32_t textureDepth;
  3178. {
  3179. const ImageBlockInfo& ibi = getBlockInfo(TextureFormat::Enum(imageContainer.m_format) );
  3180. textureWidth = bx::uint32_max(ibi.blockWidth, imageContainer.m_width >>startLod);
  3181. textureHeight = bx::uint32_max(ibi.blockHeight, imageContainer.m_height>>startLod);
  3182. textureDepth = imageContainer.m_depth;
  3183. }
  3184. GLenum target = GL_TEXTURE_2D;
  3185. if (imageContainer.m_cubeMap)
  3186. {
  3187. target = GL_TEXTURE_CUBE_MAP;
  3188. }
  3189. else if (imageContainer.m_depth > 1)
  3190. {
  3191. target = GL_TEXTURE_3D;
  3192. }
  3193. if (!init(target
  3194. , textureWidth
  3195. , textureHeight
  3196. , textureDepth
  3197. , imageContainer.m_format
  3198. , numMips
  3199. , _flags
  3200. ) )
  3201. {
  3202. return;
  3203. }
  3204. const bool computeWrite = 0 != (m_flags&BGFX_TEXTURE_COMPUTE_WRITE);
  3205. const bool srgb = 0 != (m_flags&BGFX_TEXTURE_SRGB);
  3206. target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  3207. const GLenum internalFmt = srgb
  3208. ? s_textureFormat[m_textureFormat].m_internalFmtSrgb
  3209. : s_textureFormat[m_textureFormat].m_internalFmt
  3210. ;
  3211. const bool swizzle = true
  3212. && TextureFormat::BGRA8 == m_requestedFormat
  3213. && !s_textureFormat[m_requestedFormat].m_supported
  3214. && !s_renderGL->m_textureSwizzleSupport
  3215. ;
  3216. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3217. const bool convert = false
  3218. || m_textureFormat != m_requestedFormat
  3219. || swizzle
  3220. ;
  3221. BX_TRACE("Texture%-4s %3d: %s (requested: %s), %dx%dx%d%s."
  3222. , imageContainer.m_cubeMap ? "Cube" : (1 < imageContainer.m_depth ? "3D" : "2D")
  3223. , this - s_renderGL->m_textures
  3224. , getName( (TextureFormat::Enum)m_textureFormat)
  3225. , getName( (TextureFormat::Enum)m_requestedFormat)
  3226. , textureWidth
  3227. , textureHeight
  3228. , imageContainer.m_cubeMap ? 6 : (1 < imageContainer.m_depth ? imageContainer.m_depth : 0)
  3229. , 0 != (m_flags&BGFX_TEXTURE_RT_MASK) ? " (render target)" : ""
  3230. );
  3231. BX_WARN(!convert, "Texture %s%s%s from %s to %s."
  3232. , swizzle ? "swizzle" : ""
  3233. , swizzle&&convert ? " and " : ""
  3234. , convert ? "convert" : ""
  3235. , getName( (TextureFormat::Enum)m_requestedFormat)
  3236. , getName( (TextureFormat::Enum)m_textureFormat)
  3237. );
  3238. uint8_t* temp = NULL;
  3239. if (convert)
  3240. {
  3241. temp = (uint8_t*)BX_ALLOC(g_allocator, textureWidth*textureHeight*4);
  3242. }
  3243. for (uint8_t side = 0, numSides = imageContainer.m_cubeMap ? 6 : 1; side < numSides; ++side)
  3244. {
  3245. uint32_t width = textureWidth;
  3246. uint32_t height = textureHeight;
  3247. uint32_t depth = imageContainer.m_depth;
  3248. for (uint8_t lod = 0, num = numMips; lod < num; ++lod)
  3249. {
  3250. width = bx::uint32_max(1, width);
  3251. height = bx::uint32_max(1, height);
  3252. depth = bx::uint32_max(1, depth);
  3253. ImageMip mip;
  3254. if (imageGetRawData(imageContainer, side, lod+startLod, _mem->data, _mem->size, mip) )
  3255. {
  3256. if (compressed
  3257. && !convert)
  3258. {
  3259. compressedTexImage(target+side
  3260. , lod
  3261. , internalFmt
  3262. , width
  3263. , height
  3264. , depth
  3265. , 0
  3266. , mip.m_size
  3267. , mip.m_data
  3268. );
  3269. }
  3270. else
  3271. {
  3272. const uint8_t* data = mip.m_data;
  3273. if (convert)
  3274. {
  3275. imageDecodeToRgba8(temp
  3276. , mip.m_data
  3277. , mip.m_width
  3278. , mip.m_height
  3279. , mip.m_width*4
  3280. , mip.m_format
  3281. );
  3282. data = temp;
  3283. }
  3284. texImage(target+side
  3285. , lod
  3286. , internalFmt
  3287. , width
  3288. , height
  3289. , depth
  3290. , 0
  3291. , m_fmt
  3292. , m_type
  3293. , data
  3294. );
  3295. }
  3296. }
  3297. else if (!computeWrite)
  3298. {
  3299. if (compressed)
  3300. {
  3301. uint32_t size = bx::uint32_max(1, (width + 3)>>2)
  3302. * bx::uint32_max(1, (height + 3)>>2)
  3303. * 4*4*getBitsPerPixel(TextureFormat::Enum(m_textureFormat) )/8
  3304. ;
  3305. compressedTexImage(target+side
  3306. , lod
  3307. , internalFmt
  3308. , width
  3309. , height
  3310. , depth
  3311. , 0
  3312. , size
  3313. , NULL
  3314. );
  3315. }
  3316. else
  3317. {
  3318. texImage(target+side
  3319. , lod
  3320. , internalFmt
  3321. , width
  3322. , height
  3323. , depth
  3324. , 0
  3325. , m_fmt
  3326. , m_type
  3327. , NULL
  3328. );
  3329. }
  3330. }
  3331. width >>= 1;
  3332. height >>= 1;
  3333. depth >>= 1;
  3334. }
  3335. }
  3336. if (NULL != temp)
  3337. {
  3338. BX_FREE(g_allocator, temp);
  3339. }
  3340. }
  3341. GL_CHECK(glBindTexture(m_target, 0) );
  3342. }
  3343. void TextureGL::destroy()
  3344. {
  3345. if (0 != m_id)
  3346. {
  3347. GL_CHECK(glBindTexture(m_target, 0) );
  3348. GL_CHECK(glDeleteTextures(1, &m_id) );
  3349. m_id = 0;
  3350. }
  3351. if (0 != m_rbo)
  3352. {
  3353. GL_CHECK(glDeleteRenderbuffers(1, &m_rbo) );
  3354. m_rbo = 0;
  3355. }
  3356. }
  3357. void TextureGL::update(uint8_t _side, uint8_t _mip, const Rect& _rect, uint16_t _z, uint16_t _depth, uint16_t _pitch, const Memory* _mem)
  3358. {
  3359. BX_UNUSED(_z, _depth);
  3360. const uint32_t bpp = getBitsPerPixel(TextureFormat::Enum(m_textureFormat) );
  3361. const uint32_t rectpitch = _rect.m_width*bpp/8;
  3362. uint32_t srcpitch = UINT16_MAX == _pitch ? rectpitch : _pitch;
  3363. GL_CHECK(glBindTexture(m_target, m_id) );
  3364. GL_CHECK(glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  3365. GLenum target = GL_TEXTURE_CUBE_MAP == m_target ? GL_TEXTURE_CUBE_MAP_POSITIVE_X : m_target;
  3366. const bool swizzle = true
  3367. && TextureFormat::BGRA8 == m_requestedFormat
  3368. && !s_textureFormat[m_requestedFormat].m_supported
  3369. && !s_renderGL->m_textureSwizzleSupport
  3370. ;
  3371. const bool unpackRowLength = BX_IGNORE_C4127(!!BGFX_CONFIG_RENDERER_OPENGL || s_extension[Extension::EXT_unpack_subimage].m_supported);
  3372. const bool compressed = isCompressed(TextureFormat::Enum(m_requestedFormat) );
  3373. const bool convert = false
  3374. || (compressed && m_textureFormat != m_requestedFormat)
  3375. || swizzle
  3376. ;
  3377. const uint32_t width = _rect.m_width;
  3378. const uint32_t height = _rect.m_height;
  3379. uint8_t* temp = NULL;
  3380. if (convert
  3381. || !unpackRowLength)
  3382. {
  3383. temp = (uint8_t*)BX_ALLOC(g_allocator, rectpitch*height);
  3384. }
  3385. else if (unpackRowLength)
  3386. {
  3387. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, srcpitch*8/bpp) );
  3388. }
  3389. if (compressed)
  3390. {
  3391. const uint8_t* data = _mem->data;
  3392. if (!unpackRowLength)
  3393. {
  3394. imageCopy(width, height, bpp, srcpitch, data, temp);
  3395. data = temp;
  3396. }
  3397. GL_CHECK(compressedTexSubImage(target+_side
  3398. , _mip
  3399. , _rect.m_x
  3400. , _rect.m_y
  3401. , _z
  3402. , _rect.m_width
  3403. , _rect.m_height
  3404. , _depth
  3405. , m_fmt
  3406. , _mem->size
  3407. , data
  3408. ) );
  3409. }
  3410. else
  3411. {
  3412. const uint8_t* data = _mem->data;
  3413. if (convert)
  3414. {
  3415. imageDecodeToRgba8(temp, data, width, height, srcpitch, m_requestedFormat);
  3416. data = temp;
  3417. srcpitch = rectpitch;
  3418. }
  3419. if (!unpackRowLength
  3420. && !convert)
  3421. {
  3422. imageCopy(width, height, bpp, srcpitch, data, temp);
  3423. data = temp;
  3424. }
  3425. GL_CHECK(texSubImage(target+_side
  3426. , _mip
  3427. , _rect.m_x
  3428. , _rect.m_y
  3429. , _z
  3430. , _rect.m_width
  3431. , _rect.m_height
  3432. , _depth
  3433. , m_fmt
  3434. , m_type
  3435. , data
  3436. ) );
  3437. }
  3438. if (!convert
  3439. && unpackRowLength)
  3440. {
  3441. GL_CHECK(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0) );
  3442. }
  3443. if (NULL != temp)
  3444. {
  3445. BX_FREE(g_allocator, temp);
  3446. }
  3447. }
  3448. void TextureGL::setSamplerState(uint32_t _flags)
  3449. {
  3450. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30)
  3451. && !s_textureFilter[m_textureFormat])
  3452. {
  3453. // Force point sampling when texture format doesn't support linear sampling.
  3454. _flags &= 0
  3455. | BGFX_TEXTURE_MIN_MASK
  3456. | BGFX_TEXTURE_MAG_MASK
  3457. | BGFX_TEXTURE_MIP_MASK
  3458. ;
  3459. _flags |= 0
  3460. | BGFX_TEXTURE_MIN_POINT
  3461. | BGFX_TEXTURE_MAG_POINT
  3462. | BGFX_TEXTURE_MIP_POINT
  3463. ;
  3464. }
  3465. const uint32_t flags = (0 != (BGFX_SAMPLER_DEFAULT_FLAGS & _flags) ? m_flags : _flags) & BGFX_TEXTURE_SAMPLER_BITS_MASK;
  3466. if (flags != m_currentFlags)
  3467. {
  3468. const GLenum target = m_target;
  3469. const uint8_t numMips = m_numMips;
  3470. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_S, s_textureAddress[(flags&BGFX_TEXTURE_U_MASK)>>BGFX_TEXTURE_U_SHIFT]) );
  3471. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_T, s_textureAddress[(flags&BGFX_TEXTURE_V_MASK)>>BGFX_TEXTURE_V_SHIFT]) );
  3472. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL || BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3473. || s_extension[Extension::APPLE_texture_max_level].m_supported)
  3474. {
  3475. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAX_LEVEL, numMips-1) );
  3476. }
  3477. if (target == GL_TEXTURE_3D)
  3478. {
  3479. GL_CHECK(glTexParameteri(target, GL_TEXTURE_WRAP_R, s_textureAddress[(flags&BGFX_TEXTURE_W_MASK)>>BGFX_TEXTURE_W_SHIFT]) );
  3480. }
  3481. GLenum magFilter;
  3482. GLenum minFilter;
  3483. getFilters(flags, 1 < numMips, magFilter, minFilter);
  3484. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MAG_FILTER, magFilter) );
  3485. GL_CHECK(glTexParameteri(target, GL_TEXTURE_MIN_FILTER, minFilter) );
  3486. if (0 != (flags & (BGFX_TEXTURE_MIN_ANISOTROPIC|BGFX_TEXTURE_MAG_ANISOTROPIC) )
  3487. && 0.0f < s_renderGL->m_maxAnisotropy)
  3488. {
  3489. GL_CHECK(glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, s_renderGL->m_maxAnisotropy) );
  3490. }
  3491. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30)
  3492. || s_renderGL->m_shadowSamplersSupport)
  3493. {
  3494. const uint32_t cmpFunc = (flags&BGFX_TEXTURE_COMPARE_MASK)>>BGFX_TEXTURE_COMPARE_SHIFT;
  3495. if (0 == cmpFunc)
  3496. {
  3497. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_NONE) );
  3498. }
  3499. else
  3500. {
  3501. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE) );
  3502. GL_CHECK(glTexParameteri(m_target, GL_TEXTURE_COMPARE_FUNC, s_cmpFunc[cmpFunc]) );
  3503. }
  3504. }
  3505. m_currentFlags = flags;
  3506. }
  3507. }
  3508. void TextureGL::commit(uint32_t _stage, uint32_t _flags)
  3509. {
  3510. GL_CHECK(glActiveTexture(GL_TEXTURE0+_stage) );
  3511. GL_CHECK(glBindTexture(m_target, m_id) );
  3512. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  3513. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  3514. {
  3515. // GLES2 doesn't have support for sampler object.
  3516. setSamplerState(_flags);
  3517. }
  3518. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3519. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL < 31) )
  3520. {
  3521. // In case that GL 2.1 sampler object is supported via extension.
  3522. if (s_renderGL->m_samplerObjectSupport)
  3523. {
  3524. s_renderGL->setSamplerState(_stage, m_numMips, _flags);
  3525. }
  3526. else
  3527. {
  3528. setSamplerState(_flags);
  3529. }
  3530. }
  3531. else
  3532. {
  3533. // Everything else has sampler object.
  3534. s_renderGL->setSamplerState(_stage, m_numMips, _flags);
  3535. }
  3536. }
  3537. void writeString(bx::WriterI* _writer, const char* _str)
  3538. {
  3539. bx::write(_writer, _str, (int32_t)strlen(_str) );
  3540. }
  3541. void writeStringf(bx::WriterI* _writer, const char* _format, ...)
  3542. {
  3543. char temp[512];
  3544. va_list argList;
  3545. va_start(argList, _format);
  3546. int len = bx::vsnprintf(temp, BX_COUNTOF(temp), _format, argList);
  3547. va_end(argList);
  3548. bx::write(_writer, temp, len);
  3549. }
  3550. void strins(char* _str, const char* _insert)
  3551. {
  3552. size_t len = strlen(_insert);
  3553. memmove(&_str[len], _str, strlen(_str)+1);
  3554. memcpy(_str, _insert, len);
  3555. }
  3556. void ShaderGL::create(Memory* _mem)
  3557. {
  3558. bx::MemoryReader reader(_mem->data, _mem->size);
  3559. m_hash = bx::hashMurmur2A(_mem->data, _mem->size);
  3560. uint32_t magic;
  3561. bx::read(&reader, magic);
  3562. switch (magic)
  3563. {
  3564. case BGFX_CHUNK_MAGIC_CSH: m_type = GL_COMPUTE_SHADER; break;
  3565. case BGFX_CHUNK_MAGIC_FSH: m_type = GL_FRAGMENT_SHADER; break;
  3566. case BGFX_CHUNK_MAGIC_VSH: m_type = GL_VERTEX_SHADER; break;
  3567. default:
  3568. BGFX_FATAL(false, Fatal::InvalidShader, "Unknown shader format %x.", magic);
  3569. break;
  3570. }
  3571. uint32_t iohash;
  3572. bx::read(&reader, iohash);
  3573. uint16_t count;
  3574. bx::read(&reader, count);
  3575. BX_TRACE("%s Shader consts %d"
  3576. , BGFX_CHUNK_MAGIC_FSH == magic ? "Fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "Vertex" : "Compute"
  3577. , count
  3578. );
  3579. for (uint32_t ii = 0; ii < count; ++ii)
  3580. {
  3581. uint8_t nameSize;
  3582. bx::read(&reader, nameSize);
  3583. char name[256];
  3584. bx::read(&reader, &name, nameSize);
  3585. name[nameSize] = '\0';
  3586. uint8_t type;
  3587. bx::read(&reader, type);
  3588. uint8_t num;
  3589. bx::read(&reader, num);
  3590. uint16_t regIndex;
  3591. bx::read(&reader, regIndex);
  3592. uint16_t regCount;
  3593. bx::read(&reader, regCount);
  3594. }
  3595. uint32_t shaderSize;
  3596. bx::read(&reader, shaderSize);
  3597. m_id = glCreateShader(m_type);
  3598. BX_WARN(0 != m_id, "Failed to create %s shader."
  3599. , BGFX_CHUNK_MAGIC_FSH == magic ? "fragment" : BGFX_CHUNK_MAGIC_VSH == magic ? "vertex" : "compute"
  3600. );
  3601. const char* code = (const char*)reader.getDataPtr();
  3602. if (0 != m_id)
  3603. {
  3604. if (GL_COMPUTE_SHADER != m_type)
  3605. {
  3606. int32_t codeLen = (int32_t)strlen(code);
  3607. int32_t tempLen = codeLen + (4<<10);
  3608. char* temp = (char*)alloca(tempLen);
  3609. bx::StaticMemoryBlockWriter writer(temp, tempLen);
  3610. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES)
  3611. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES < 30) )
  3612. {
  3613. writeString(&writer
  3614. , "#define flat\n"
  3615. "#define smooth\n"
  3616. "#define noperspective\n"
  3617. );
  3618. bool usesDerivatives = s_extension[Extension::OES_standard_derivatives].m_supported
  3619. && bx::findIdentifierMatch(code, s_OES_standard_derivatives)
  3620. ;
  3621. bool usesFragData = !!bx::findIdentifierMatch(code, "gl_FragData");
  3622. bool usesFragDepth = !!bx::findIdentifierMatch(code, "gl_FragDepth");
  3623. bool usesShadowSamplers = !!bx::findIdentifierMatch(code, s_EXT_shadow_samplers);
  3624. bool usesTexture3D = s_extension[Extension::OES_texture_3D].m_supported
  3625. && bx::findIdentifierMatch(code, s_OES_texture_3D)
  3626. ;
  3627. bool usesTextureLod = !!bx::findIdentifierMatch(code, s_EXT_shader_texture_lod);
  3628. bool usesFragmentOrdering = !!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering");
  3629. if (usesDerivatives)
  3630. {
  3631. writeString(&writer, "#extension GL_OES_standard_derivatives : enable\n");
  3632. }
  3633. if (usesFragData)
  3634. {
  3635. BX_WARN(s_extension[Extension::EXT_draw_buffers ].m_supported
  3636. || s_extension[Extension::WEBGL_draw_buffers].m_supported
  3637. , "EXT_draw_buffers is used but not supported by GLES2 driver."
  3638. );
  3639. writeString(&writer
  3640. , "#extension GL_EXT_draw_buffers : enable\n"
  3641. );
  3642. }
  3643. bool insertFragDepth = false;
  3644. if (usesFragDepth)
  3645. {
  3646. BX_WARN(s_extension[Extension::EXT_frag_depth].m_supported, "EXT_frag_depth is used but not supported by GLES2 driver.");
  3647. if (s_extension[Extension::EXT_frag_depth].m_supported)
  3648. {
  3649. writeString(&writer
  3650. , "#extension GL_EXT_frag_depth : enable\n"
  3651. "#define bgfx_FragDepth gl_FragDepthEXT\n"
  3652. );
  3653. char str[128];
  3654. bx::snprintf(str, BX_COUNTOF(str), "%s float gl_FragDepthEXT;\n"
  3655. , s_extension[Extension::OES_fragment_precision_high].m_supported ? "highp" : "mediump"
  3656. );
  3657. writeString(&writer, str);
  3658. }
  3659. else
  3660. {
  3661. insertFragDepth = true;
  3662. }
  3663. }
  3664. if (usesShadowSamplers)
  3665. {
  3666. if (s_renderGL->m_shadowSamplersSupport)
  3667. {
  3668. writeString(&writer
  3669. , "#extension GL_EXT_shadow_samplers : enable\n"
  3670. "#define shadow2D shadow2DEXT\n"
  3671. "#define shadow2DProj shadow2DProjEXT\n"
  3672. );
  3673. }
  3674. else
  3675. {
  3676. writeString(&writer
  3677. , "#define sampler2DShadow sampler2D\n"
  3678. "#define shadow2D(_sampler, _coord) step(_coord.z, texture2D(_sampler, _coord.xy).x)\n"
  3679. "#define shadow2DProj(_sampler, _coord) step(_coord.z/_coord.w, texture2DProj(_sampler, _coord).x)\n"
  3680. );
  3681. }
  3682. }
  3683. if (usesTexture3D)
  3684. {
  3685. writeString(&writer, "#extension GL_OES_texture_3D : enable\n");
  3686. }
  3687. if (usesTextureLod)
  3688. {
  3689. BX_WARN(s_extension[Extension::EXT_shader_texture_lod].m_supported, "EXT_shader_texture_lod is used but not supported by GLES2 driver.");
  3690. if (s_extension[Extension::EXT_shader_texture_lod].m_supported)
  3691. {
  3692. writeString(&writer
  3693. , "#extension GL_EXT_shader_texture_lod : enable\n"
  3694. "#define texture2DLod texture2DLodEXT\n"
  3695. "#define texture2DProjLod texture2DProjLodEXT\n"
  3696. "#define textureCubeLod textureCubeLodEXT\n"
  3697. );
  3698. }
  3699. else
  3700. {
  3701. writeString(&writer
  3702. , "#define texture2DLod(_sampler, _coord, _level) texture2D(_sampler, _coord)\n"
  3703. "#define texture2DProjLod(_sampler, _coord, _level) texture2DProj(_sampler, _coord)\n"
  3704. "#define textureCubeLod(_sampler, _coord, _level) textureCube(_sampler, _coord)\n"
  3705. );
  3706. }
  3707. }
  3708. if (usesFragmentOrdering)
  3709. {
  3710. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  3711. {
  3712. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  3713. }
  3714. else
  3715. {
  3716. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  3717. }
  3718. }
  3719. writeStringf(&writer, "precision %s float;\n"
  3720. , m_type == GL_FRAGMENT_SHADER ? "mediump" : "highp"
  3721. );
  3722. bx::write(&writer, code, codeLen);
  3723. bx::write(&writer, '\0');
  3724. if (insertFragDepth)
  3725. {
  3726. char* entry = strstr(temp, "void main ()");
  3727. if (NULL != entry)
  3728. {
  3729. char* brace = strstr(entry, "{");
  3730. if (NULL != brace)
  3731. {
  3732. const char* end = bx::strmb(brace, '{', '}');
  3733. if (NULL != end)
  3734. {
  3735. strins(brace+1, "\n float bgfx_FragDepth = 0.0;\n");
  3736. }
  3737. }
  3738. }
  3739. }
  3740. // Replace all instances of gl_FragDepth with bgfx_FragDepth.
  3741. for (const char* fragDepth = bx::findIdentifierMatch(temp, "gl_FragDepth"); NULL != fragDepth; fragDepth = bx::findIdentifierMatch(fragDepth, "gl_FragDepth") )
  3742. {
  3743. char* insert = const_cast<char*>(fragDepth);
  3744. strins(insert, "bg");
  3745. memcpy(insert + 2, "fx", 2);
  3746. }
  3747. }
  3748. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  3749. && BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL <= 21) )
  3750. {
  3751. bool usesTextureLod = true
  3752. && s_extension[Extension::ARB_shader_texture_lod].m_supported
  3753. && bx::findIdentifierMatch(code, s_ARB_shader_texture_lod)
  3754. ;
  3755. bool usesIUsamplers = !!bx::findIdentifierMatch(code, s_uisamplers);
  3756. uint32_t version = usesIUsamplers
  3757. ? 130
  3758. : (usesTextureLod ? 120 : 0)
  3759. ;
  3760. if (0 != version)
  3761. {
  3762. writeStringf(&writer, "#version %d\n", version);
  3763. }
  3764. if (usesTextureLod)
  3765. {
  3766. if (m_type == GL_FRAGMENT_SHADER)
  3767. {
  3768. writeString(&writer, "#extension GL_ARB_shader_texture_lod : enable\n");
  3769. }
  3770. }
  3771. if (130 <= version)
  3772. {
  3773. if (m_type == GL_FRAGMENT_SHADER)
  3774. {
  3775. writeString(&writer, "#define varying in\n");
  3776. }
  3777. else
  3778. {
  3779. writeString(&writer, "#define attribute in\n");
  3780. writeString(&writer, "#define varying out\n");
  3781. }
  3782. uint32_t fragData = 0;
  3783. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  3784. {
  3785. for (uint32_t ii = 0, num = g_caps.maxFBAttachments; ii < num; ++ii)
  3786. {
  3787. char tmpFragData[16];
  3788. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  3789. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  3790. }
  3791. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  3792. }
  3793. if (0 != fragData)
  3794. {
  3795. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  3796. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  3797. }
  3798. else
  3799. {
  3800. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  3801. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  3802. }
  3803. }
  3804. writeString(&writer
  3805. , "#define lowp\n"
  3806. "#define mediump\n"
  3807. "#define highp\n"
  3808. "#define flat\n"
  3809. "#define smooth\n"
  3810. "#define noperspective\n"
  3811. );
  3812. bx::write(&writer, code, codeLen);
  3813. bx::write(&writer, '\0');
  3814. }
  3815. else if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL >= 31)
  3816. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3817. {
  3818. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3819. {
  3820. writeString(&writer
  3821. , "#version 300 es\n"
  3822. "precision mediump float;\n"
  3823. );
  3824. }
  3825. else
  3826. {
  3827. writeString(&writer, "#version 140\n");
  3828. }
  3829. writeString(&writer, "#define texture2DLod textureLod\n");
  3830. writeString(&writer, "#define texture3DLod textureLod\n");
  3831. writeString(&writer, "#define textureCubeLod textureLod\n");
  3832. if (m_type == GL_FRAGMENT_SHADER)
  3833. {
  3834. writeString(&writer, "#define varying in\n");
  3835. writeString(&writer, "#define texture2D texture\n");
  3836. writeString(&writer, "#define texture2DProj textureProj\n");
  3837. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  3838. {
  3839. writeString(&writer, "#define shadow2D(_sampler, _coord) vec2(textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  3840. writeString(&writer, "#define shadow2DProj(_sampler, _coord) vec2(textureProj(_sampler, _coord) ) )\n");
  3841. }
  3842. else
  3843. {
  3844. writeString(&writer, "#define shadow2D(_sampler, _coord) (textureProj(_sampler, vec4(_coord, 1.0) ) )\n");
  3845. writeString(&writer, "#define shadow2DProj(_sampler, _coord) (textureProj(_sampler, _coord) ) )\n");
  3846. }
  3847. writeString(&writer, "#define texture3D texture\n");
  3848. writeString(&writer, "#define textureCube texture\n");
  3849. uint32_t fragData = 0;
  3850. if (!!bx::findIdentifierMatch(code, "gl_FragData") )
  3851. {
  3852. for (uint32_t ii = 0, num = g_caps.maxFBAttachments; ii < num; ++ii)
  3853. {
  3854. char tmpFragData[16];
  3855. bx::snprintf(tmpFragData, BX_COUNTOF(tmpFragData), "gl_FragData[%d]", ii);
  3856. fragData = bx::uint32_max(fragData, NULL == strstr(code, tmpFragData) ? 0 : ii+1);
  3857. }
  3858. BGFX_FATAL(0 != fragData, Fatal::InvalidShader, "Unable to find and patch gl_FragData!");
  3859. }
  3860. if (!!bx::findIdentifierMatch(code, "beginFragmentShaderOrdering") )
  3861. {
  3862. if (s_extension[Extension::INTEL_fragment_shader_ordering].m_supported)
  3863. {
  3864. writeString(&writer, "#extension GL_INTEL_fragment_shader_ordering : enable\n");
  3865. }
  3866. else
  3867. {
  3868. writeString(&writer, "#define beginFragmentShaderOrdering()\n");
  3869. }
  3870. }
  3871. if (0 != fragData)
  3872. {
  3873. writeStringf(&writer, "out vec4 bgfx_FragData[%d];\n", fragData);
  3874. writeString(&writer, "#define gl_FragData bgfx_FragData\n");
  3875. }
  3876. else
  3877. {
  3878. writeString(&writer, "out vec4 bgfx_FragColor;\n");
  3879. writeString(&writer, "#define gl_FragColor bgfx_FragColor\n");
  3880. }
  3881. }
  3882. else
  3883. {
  3884. writeString(&writer, "#define attribute in\n");
  3885. writeString(&writer, "#define varying out\n");
  3886. }
  3887. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 30) )
  3888. {
  3889. writeString(&writer
  3890. , "#define lowp\n"
  3891. "#define mediump\n"
  3892. "#define highp\n"
  3893. );
  3894. }
  3895. bx::write(&writer, code, codeLen);
  3896. bx::write(&writer, '\0');
  3897. }
  3898. code = temp;
  3899. }
  3900. GL_CHECK(glShaderSource(m_id, 1, (const GLchar**)&code, NULL) );
  3901. GL_CHECK(glCompileShader(m_id) );
  3902. GLint compiled = 0;
  3903. GL_CHECK(glGetShaderiv(m_id, GL_COMPILE_STATUS, &compiled) );
  3904. if (0 == compiled)
  3905. {
  3906. BX_TRACE("\n####\n%s\n####", code);
  3907. GLsizei len;
  3908. char log[1024];
  3909. GL_CHECK(glGetShaderInfoLog(m_id, sizeof(log), &len, log) );
  3910. BX_TRACE("Failed to compile shader. %d: %s", compiled, log);
  3911. GL_CHECK(glDeleteShader(m_id) );
  3912. m_id = 0;
  3913. BGFX_FATAL(false, bgfx::Fatal::InvalidShader, "Failed to compile shader.");
  3914. }
  3915. else if (BX_ENABLED(BGFX_CONFIG_DEBUG)
  3916. && s_extension[Extension::ANGLE_translated_shader_source].m_supported
  3917. && NULL != glGetTranslatedShaderSourceANGLE)
  3918. {
  3919. GLsizei len;
  3920. GL_CHECK(glGetShaderiv(m_id, GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE, &len) );
  3921. char* source = (char*)alloca(len);
  3922. GL_CHECK(glGetTranslatedShaderSourceANGLE(m_id, len, &len, source) );
  3923. BX_TRACE("ANGLE source (len: %d):\n%s\n####", len, source);
  3924. }
  3925. }
  3926. }
  3927. void ShaderGL::destroy()
  3928. {
  3929. if (0 != m_id)
  3930. {
  3931. GL_CHECK(glDeleteShader(m_id) );
  3932. m_id = 0;
  3933. }
  3934. }
  3935. static void frameBufferValidate()
  3936. {
  3937. GLenum complete = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  3938. BX_CHECK(GL_FRAMEBUFFER_COMPLETE == complete
  3939. , "glCheckFramebufferStatus failed 0x%08x: %s"
  3940. , complete
  3941. , glEnumName(complete)
  3942. );
  3943. BX_UNUSED(complete);
  3944. }
  3945. void FrameBufferGL::create(uint8_t _num, const TextureHandle* _handles)
  3946. {
  3947. GL_CHECK(glGenFramebuffers(1, &m_fbo[0]) );
  3948. m_numTh = _num;
  3949. memcpy(m_th, _handles, _num*sizeof(TextureHandle) );
  3950. postReset();
  3951. }
  3952. void FrameBufferGL::postReset()
  3953. {
  3954. if (0 != m_fbo[0])
  3955. {
  3956. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[0]) );
  3957. bool needResolve = false;
  3958. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS];
  3959. uint32_t colorIdx = 0;
  3960. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  3961. {
  3962. TextureHandle handle = m_th[ii];
  3963. if (isValid(handle) )
  3964. {
  3965. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  3966. if (0 == colorIdx)
  3967. {
  3968. m_width = texture.m_width;
  3969. m_height = texture.m_height;
  3970. }
  3971. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  3972. TextureFormat::Enum format = (TextureFormat::Enum)texture.m_textureFormat;
  3973. if (isDepth(format) )
  3974. {
  3975. const ImageBlockInfo& info = getBlockInfo(format);
  3976. if (0 < info.stencilBits)
  3977. {
  3978. attachment = GL_DEPTH_STENCIL_ATTACHMENT;
  3979. }
  3980. else if (0 == info.depthBits)
  3981. {
  3982. attachment = GL_STENCIL_ATTACHMENT;
  3983. }
  3984. else
  3985. {
  3986. attachment = GL_DEPTH_ATTACHMENT;
  3987. }
  3988. }
  3989. else
  3990. {
  3991. buffers[colorIdx] = attachment;
  3992. ++colorIdx;
  3993. }
  3994. if (0 != texture.m_rbo)
  3995. {
  3996. GL_CHECK(glFramebufferRenderbuffer(GL_FRAMEBUFFER
  3997. , attachment
  3998. , GL_RENDERBUFFER
  3999. , texture.m_rbo
  4000. ) );
  4001. }
  4002. else
  4003. {
  4004. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  4005. , attachment
  4006. , texture.m_target
  4007. , texture.m_id
  4008. , 0
  4009. ) );
  4010. }
  4011. needResolve |= (0 != texture.m_rbo) && (0 != texture.m_id);
  4012. }
  4013. }
  4014. m_num = uint8_t(colorIdx);
  4015. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) )
  4016. {
  4017. if (0 == colorIdx)
  4018. {
  4019. // When only depth is attached disable draw buffer to avoid
  4020. // GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER.
  4021. GL_CHECK(glDrawBuffer(GL_NONE) );
  4022. }
  4023. else
  4024. {
  4025. GL_CHECK(glDrawBuffers(colorIdx, buffers) );
  4026. }
  4027. // Disable read buffer to avoid GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER.
  4028. GL_CHECK(glReadBuffer(GL_NONE) );
  4029. }
  4030. frameBufferValidate();
  4031. if (needResolve)
  4032. {
  4033. GL_CHECK(glGenFramebuffers(1, &m_fbo[1]) );
  4034. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_fbo[1]) );
  4035. colorIdx = 0;
  4036. for (uint32_t ii = 0; ii < m_numTh; ++ii)
  4037. {
  4038. TextureHandle handle = m_th[ii];
  4039. if (isValid(handle) )
  4040. {
  4041. const TextureGL& texture = s_renderGL->m_textures[handle.idx];
  4042. if (0 != texture.m_id)
  4043. {
  4044. GLenum attachment = GL_COLOR_ATTACHMENT0 + colorIdx;
  4045. if (!isDepth( (TextureFormat::Enum)texture.m_textureFormat) )
  4046. {
  4047. ++colorIdx;
  4048. GL_CHECK(glFramebufferTexture2D(GL_FRAMEBUFFER
  4049. , attachment
  4050. , texture.m_target
  4051. , texture.m_id
  4052. , 0
  4053. ) );
  4054. }
  4055. }
  4056. }
  4057. }
  4058. frameBufferValidate();
  4059. }
  4060. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  4061. }
  4062. }
  4063. void FrameBufferGL::create(uint16_t _denseIdx, void* _nwh, uint32_t _width, uint32_t _height, TextureFormat::Enum _depthFormat)
  4064. {
  4065. BX_UNUSED(_depthFormat);
  4066. m_swapChain = s_renderGL->m_glctx.createSwapChain(_nwh);
  4067. m_width = _width;
  4068. m_height = _height;
  4069. m_denseIdx = _denseIdx;
  4070. }
  4071. uint16_t FrameBufferGL::destroy()
  4072. {
  4073. if (0 != m_num)
  4074. {
  4075. GL_CHECK(glDeleteFramebuffers(0 == m_fbo[1] ? 1 : 2, m_fbo) );
  4076. m_num = 0;
  4077. }
  4078. if (NULL != m_swapChain)
  4079. {
  4080. s_renderGL->m_glctx.destroySwapChain(m_swapChain);
  4081. m_swapChain = NULL;
  4082. }
  4083. memset(m_fbo, 0, sizeof(m_fbo) );
  4084. uint16_t denseIdx = m_denseIdx;
  4085. m_denseIdx = UINT16_MAX;
  4086. return denseIdx;
  4087. }
  4088. void FrameBufferGL::resolve()
  4089. {
  4090. if (0 != m_fbo[1])
  4091. {
  4092. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  4093. GL_CHECK(glReadBuffer(GL_COLOR_ATTACHMENT0) );
  4094. GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo[1]) );
  4095. GL_CHECK(glBlitFramebuffer(0
  4096. , 0
  4097. , m_width
  4098. , m_height
  4099. , 0
  4100. , 0
  4101. , m_width
  4102. , m_height
  4103. , GL_COLOR_BUFFER_BIT
  4104. , GL_LINEAR
  4105. ) );
  4106. GL_CHECK(glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo[0]) );
  4107. GL_CHECK(glReadBuffer(GL_NONE) );
  4108. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, s_renderGL->m_msaaBackBufferFbo) );
  4109. }
  4110. }
  4111. void FrameBufferGL::discard(uint16_t _flags)
  4112. {
  4113. GLenum buffers[BGFX_CONFIG_MAX_FRAME_BUFFER_ATTACHMENTS+2];
  4114. uint32_t idx = 0;
  4115. if (BGFX_CLEAR_NONE != (_flags & BGFX_CLEAR_DISCARD_COLOR_MASK) )
  4116. {
  4117. for (uint32_t ii = 0, num = m_num; ii < num; ++ii)
  4118. {
  4119. if (BGFX_CLEAR_NONE != (_flags & (BGFX_CLEAR_DISCARD_COLOR_0<<ii) ) )
  4120. {
  4121. buffers[idx++] = GL_COLOR_ATTACHMENT0 + ii;
  4122. }
  4123. }
  4124. }
  4125. uint32_t dsFlags = _flags & (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL);
  4126. if (BGFX_CLEAR_NONE != dsFlags)
  4127. {
  4128. if ( (BGFX_CLEAR_DISCARD_DEPTH|BGFX_CLEAR_DISCARD_STENCIL) == dsFlags)
  4129. {
  4130. buffers[idx++] = GL_DEPTH_STENCIL_ATTACHMENT;
  4131. }
  4132. else if (BGFX_CLEAR_DISCARD_DEPTH == dsFlags)
  4133. {
  4134. buffers[idx++] = GL_DEPTH_ATTACHMENT;
  4135. }
  4136. else if (BGFX_CLEAR_DISCARD_STENCIL == dsFlags)
  4137. {
  4138. buffers[idx++] = GL_STENCIL_ATTACHMENT;
  4139. }
  4140. }
  4141. GL_CHECK(glInvalidateFramebuffer(GL_FRAMEBUFFER, idx, buffers) );
  4142. }
  4143. void RendererContextGL::submit(Frame* _render, ClearQuad& _clearQuad, TextVideoMemBlitter& _textVideoMemBlitter)
  4144. {
  4145. if (1 < m_numWindows
  4146. && m_vaoSupport)
  4147. {
  4148. m_vaoSupport = false;
  4149. GL_CHECK(glBindVertexArray(0) );
  4150. GL_CHECK(glDeleteVertexArrays(1, &m_vao) );
  4151. m_vao = 0;
  4152. m_vaoStateCache.invalidate();
  4153. }
  4154. m_glctx.makeCurrent(NULL);
  4155. const GLuint defaultVao = m_vao;
  4156. if (0 != defaultVao)
  4157. {
  4158. GL_CHECK(glBindVertexArray(defaultVao) );
  4159. }
  4160. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_backBufferFbo) );
  4161. updateResolution(_render->m_resolution);
  4162. int64_t elapsed = -bx::getHPCounter();
  4163. int64_t captureElapsed = 0;
  4164. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4165. && (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  4166. && m_timerQuerySupport)
  4167. {
  4168. m_queries.begin(0, GL_TIME_ELAPSED);
  4169. }
  4170. if (0 < _render->m_iboffset)
  4171. {
  4172. TransientIndexBuffer* ib = _render->m_transientIb;
  4173. m_indexBuffers[ib->handle.idx].update(0, _render->m_iboffset, ib->data);
  4174. }
  4175. if (0 < _render->m_vboffset)
  4176. {
  4177. TransientVertexBuffer* vb = _render->m_transientVb;
  4178. m_vertexBuffers[vb->handle.idx].update(0, _render->m_vboffset, vb->data);
  4179. }
  4180. _render->sort();
  4181. RenderDraw currentState;
  4182. currentState.clear();
  4183. currentState.m_flags = BGFX_STATE_NONE;
  4184. currentState.m_stencil = packStencil(BGFX_STENCIL_NONE, BGFX_STENCIL_NONE);
  4185. _render->m_hmdInitialized = m_ovr.isInitialized();
  4186. const bool hmdEnabled = m_ovr.isEnabled() || m_ovr.isDebug();
  4187. ViewState viewState(_render, hmdEnabled);
  4188. uint16_t programIdx = invalidHandle;
  4189. SortKey key;
  4190. uint8_t view = 0xff;
  4191. FrameBufferHandle fbh = BGFX_INVALID_HANDLE;
  4192. int32_t height = hmdEnabled
  4193. ? _render->m_hmd.height
  4194. : _render->m_resolution.m_height
  4195. ;
  4196. uint32_t blendFactor = 0;
  4197. uint8_t primIndex;
  4198. {
  4199. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : 0;
  4200. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  4201. }
  4202. PrimInfo prim = s_primInfo[primIndex];
  4203. uint32_t baseVertex = 0;
  4204. GLuint currentVao = 0;
  4205. bool wasCompute = false;
  4206. bool viewHasScissor = false;
  4207. Rect viewScissorRect;
  4208. viewScissorRect.clear();
  4209. uint16_t discardFlags = BGFX_CLEAR_NONE;
  4210. const bool blendIndependentSupported = s_extension[Extension::ARB_draw_buffers_blend].m_supported;
  4211. const bool computeSupported = (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL) && s_extension[Extension::ARB_compute_shader].m_supported)
  4212. || BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGLES >= 31)
  4213. ;
  4214. uint32_t statsNumPrimsSubmitted[BX_COUNTOF(s_primInfo)] = {};
  4215. uint32_t statsNumPrimsRendered[BX_COUNTOF(s_primInfo)] = {};
  4216. uint32_t statsNumInstances[BX_COUNTOF(s_primInfo)] = {};
  4217. uint32_t statsNumIndices = 0;
  4218. uint32_t statsKeyType[2] = {};
  4219. if (0 == (_render->m_debug&BGFX_DEBUG_IFH) )
  4220. {
  4221. GL_CHECK(glBindFramebuffer(GL_FRAMEBUFFER, m_msaaBackBufferFbo) );
  4222. bool viewRestart = false;
  4223. uint8_t eye = 0;
  4224. uint8_t restartState = 0;
  4225. viewState.m_rect = _render->m_rect[0];
  4226. int32_t numItems = _render->m_num;
  4227. for (int32_t item = 0, restartItem = numItems; item < numItems || restartItem < numItems;)
  4228. {
  4229. const bool isCompute = key.decode(_render->m_sortKeys[item], _render->m_viewRemap);
  4230. statsKeyType[isCompute]++;
  4231. const bool viewChanged = 0
  4232. || key.m_view != view
  4233. || item == numItems
  4234. ;
  4235. const RenderItem& renderItem = _render->m_renderItem[_render->m_sortValues[item] ];
  4236. ++item;
  4237. if (viewChanged)
  4238. {
  4239. if (1 == restartState)
  4240. {
  4241. restartState = 2;
  4242. item = restartItem;
  4243. restartItem = numItems;
  4244. view = 0xff;
  4245. continue;
  4246. }
  4247. view = key.m_view;
  4248. programIdx = invalidHandle;
  4249. if (_render->m_fb[view].idx != fbh.idx)
  4250. {
  4251. fbh = _render->m_fb[view];
  4252. height = hmdEnabled
  4253. ? _render->m_hmd.height
  4254. : _render->m_resolution.m_height
  4255. ;
  4256. height = setFrameBuffer(fbh, height, discardFlags);
  4257. }
  4258. viewRestart = ( (BGFX_VIEW_STEREO == (_render->m_viewFlags[view] & BGFX_VIEW_STEREO) ) );
  4259. viewRestart &= hmdEnabled;
  4260. if (viewRestart)
  4261. {
  4262. if (0 == restartState)
  4263. {
  4264. restartState = 1;
  4265. restartItem = item - 1;
  4266. }
  4267. eye = (restartState - 1) & 1;
  4268. restartState &= 1;
  4269. }
  4270. else
  4271. {
  4272. eye = 0;
  4273. }
  4274. viewState.m_rect = _render->m_rect[view];
  4275. if (viewRestart)
  4276. {
  4277. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4278. {
  4279. char* viewName = s_viewName[view];
  4280. viewName[3] = ' ';
  4281. viewName[4] = eye ? 'R' : 'L';
  4282. GL_CHECK(glInsertEventMarker(0, viewName) );
  4283. }
  4284. if (m_ovr.isEnabled() )
  4285. {
  4286. m_ovr.getViewport(eye, &viewState.m_rect);
  4287. }
  4288. else
  4289. {
  4290. viewState.m_rect.m_x = eye * (viewState.m_rect.m_width+1)/2;
  4291. viewState.m_rect.m_width /= 2;
  4292. }
  4293. }
  4294. else
  4295. {
  4296. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4297. {
  4298. char* viewName = s_viewName[view];
  4299. viewName[3] = ' ';
  4300. viewName[4] = ' ';
  4301. GL_CHECK(glInsertEventMarker(0, viewName) );
  4302. }
  4303. }
  4304. const Rect& scissorRect = _render->m_scissor[view];
  4305. viewHasScissor = !scissorRect.isZero();
  4306. viewScissorRect = viewHasScissor ? scissorRect : viewState.m_rect;
  4307. GL_CHECK(glViewport(viewState.m_rect.m_x
  4308. , height-viewState.m_rect.m_height-viewState.m_rect.m_y
  4309. , viewState.m_rect.m_width
  4310. , viewState.m_rect.m_height
  4311. ) );
  4312. Clear& clear = _render->m_clear[view];
  4313. discardFlags = clear.m_flags & BGFX_CLEAR_DISCARD_MASK;
  4314. if (BGFX_CLEAR_NONE != (clear.m_flags & BGFX_CLEAR_MASK) )
  4315. {
  4316. clearQuad(_clearQuad, viewState.m_rect, clear, height, _render->m_clearColor);
  4317. }
  4318. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  4319. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  4320. GL_CHECK(glDepthFunc(GL_LESS) );
  4321. GL_CHECK(glEnable(GL_CULL_FACE) );
  4322. GL_CHECK(glDisable(GL_BLEND) );
  4323. }
  4324. if (isCompute)
  4325. {
  4326. if (!wasCompute)
  4327. {
  4328. wasCompute = true;
  4329. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4330. {
  4331. char* viewName = s_viewName[view];
  4332. viewName[3] = 'C';
  4333. GL_CHECK(glInsertEventMarker(0, viewName) );
  4334. }
  4335. }
  4336. if (computeSupported)
  4337. {
  4338. const RenderCompute& compute = renderItem.compute;
  4339. ProgramGL& program = m_program[key.m_program];
  4340. GL_CHECK(glUseProgram(program.m_id) );
  4341. GLbitfield barrier = 0;
  4342. for (uint32_t ii = 0; ii < BGFX_MAX_COMPUTE_BINDINGS; ++ii)
  4343. {
  4344. const Binding& bind = compute.m_bind[ii];
  4345. if (invalidHandle != bind.m_idx)
  4346. {
  4347. switch (bind.m_type)
  4348. {
  4349. case Binding::Image:
  4350. {
  4351. const TextureGL& texture = m_textures[bind.m_idx];
  4352. GL_CHECK(glBindImageTexture(ii
  4353. , texture.m_id
  4354. , bind.m_un.m_compute.m_mip
  4355. , GL_FALSE
  4356. , 0
  4357. , s_access[bind.m_un.m_compute.m_access]
  4358. , s_imageFormat[bind.m_un.m_compute.m_format])
  4359. );
  4360. barrier |= GL_SHADER_IMAGE_ACCESS_BARRIER_BIT;
  4361. }
  4362. break;
  4363. case Binding::IndexBuffer:
  4364. {
  4365. const IndexBufferGL& buffer = m_indexBuffers[bind.m_idx];
  4366. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id));
  4367. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  4368. }
  4369. break;
  4370. case Binding::VertexBuffer:
  4371. {
  4372. const VertexBufferGL& buffer = m_vertexBuffers[bind.m_idx];
  4373. GL_CHECK(glBindBufferBase(GL_SHADER_STORAGE_BUFFER, ii, buffer.m_id));
  4374. barrier |= GL_SHADER_STORAGE_BARRIER_BIT;
  4375. }
  4376. break;
  4377. }
  4378. }
  4379. }
  4380. if (0 != barrier)
  4381. {
  4382. bool constantsChanged = compute.m_constBegin < compute.m_constEnd;
  4383. rendererUpdateUniforms(this, _render->m_constantBuffer, compute.m_constBegin, compute.m_constEnd);
  4384. if (constantsChanged
  4385. && NULL != program.m_constantBuffer)
  4386. {
  4387. commit(*program.m_constantBuffer);
  4388. }
  4389. viewState.setPredefined<1>(this, view, eye, program, _render, compute);
  4390. if (isValid(compute.m_indirectBuffer) )
  4391. {
  4392. const VertexBufferGL& vb = m_vertexBuffers[compute.m_indirectBuffer.idx];
  4393. if (currentState.m_indirectBuffer.idx != compute.m_indirectBuffer.idx)
  4394. {
  4395. currentState.m_indirectBuffer = compute.m_indirectBuffer;
  4396. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, vb.m_id) );
  4397. }
  4398. uint32_t numDrawIndirect = UINT16_MAX == compute.m_numIndirect
  4399. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4400. : compute.m_numIndirect
  4401. ;
  4402. uintptr_t args = compute.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4403. for (uint32_t ii = 0; ii < numDrawIndirect; ++ii)
  4404. {
  4405. GL_CHECK(glDispatchComputeIndirect(args) );
  4406. args += BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4407. }
  4408. }
  4409. else
  4410. {
  4411. if (isValid(currentState.m_indirectBuffer) )
  4412. {
  4413. currentState.m_indirectBuffer.idx = invalidHandle;
  4414. GL_CHECK(glBindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0) );
  4415. }
  4416. GL_CHECK(glDispatchCompute(compute.m_numX, compute.m_numY, compute.m_numZ) );
  4417. }
  4418. GL_CHECK(glMemoryBarrier(barrier) );
  4419. }
  4420. }
  4421. continue;
  4422. }
  4423. bool resetState = viewChanged || wasCompute;
  4424. if (wasCompute)
  4425. {
  4426. wasCompute = false;
  4427. if (BX_ENABLED(BGFX_CONFIG_DEBUG_PIX) )
  4428. {
  4429. char* viewName = s_viewName[view];
  4430. viewName[3] = ' ';
  4431. GL_CHECK(glInsertEventMarker(0, viewName) );
  4432. }
  4433. }
  4434. const RenderDraw& draw = renderItem.draw;
  4435. const uint64_t newFlags = draw.m_flags;
  4436. uint64_t changedFlags = currentState.m_flags ^ draw.m_flags;
  4437. currentState.m_flags = newFlags;
  4438. const uint64_t newStencil = draw.m_stencil;
  4439. uint64_t changedStencil = currentState.m_stencil ^ draw.m_stencil;
  4440. currentState.m_stencil = newStencil;
  4441. if (resetState)
  4442. {
  4443. currentState.clear();
  4444. currentState.m_scissor = !draw.m_scissor;
  4445. changedFlags = BGFX_STATE_MASK;
  4446. changedStencil = packStencil(BGFX_STENCIL_MASK, BGFX_STENCIL_MASK);
  4447. currentState.m_flags = newFlags;
  4448. currentState.m_stencil = newStencil;
  4449. }
  4450. uint16_t scissor = draw.m_scissor;
  4451. if (currentState.m_scissor != scissor)
  4452. {
  4453. currentState.m_scissor = scissor;
  4454. if (UINT16_MAX == scissor)
  4455. {
  4456. if (viewHasScissor)
  4457. {
  4458. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  4459. GL_CHECK(glScissor(viewScissorRect.m_x
  4460. , height-viewScissorRect.m_height-viewScissorRect.m_y
  4461. , viewScissorRect.m_width
  4462. , viewScissorRect.m_height
  4463. ) );
  4464. }
  4465. else
  4466. {
  4467. GL_CHECK(glDisable(GL_SCISSOR_TEST) );
  4468. }
  4469. }
  4470. else
  4471. {
  4472. Rect scissorRect;
  4473. scissorRect.intersect(viewScissorRect, _render->m_rectCache.m_cache[scissor]);
  4474. GL_CHECK(glEnable(GL_SCISSOR_TEST) );
  4475. GL_CHECK(glScissor(scissorRect.m_x
  4476. , height-scissorRect.m_height-scissorRect.m_y
  4477. , scissorRect.m_width
  4478. , scissorRect.m_height
  4479. ) );
  4480. }
  4481. }
  4482. if (0 != changedStencil)
  4483. {
  4484. if (0 != newStencil)
  4485. {
  4486. GL_CHECK(glEnable(GL_STENCIL_TEST) );
  4487. uint32_t bstencil = unpackStencil(1, newStencil);
  4488. uint8_t frontAndBack = bstencil != BGFX_STENCIL_NONE && bstencil != unpackStencil(0, newStencil);
  4489. // uint32_t bchanged = unpackStencil(1, changedStencil);
  4490. // if (BGFX_STENCIL_FUNC_RMASK_MASK & bchanged)
  4491. // {
  4492. // uint32_t wmask = (bstencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  4493. // GL_CHECK(glStencilMask(wmask) );
  4494. // }
  4495. for (uint8_t ii = 0, num = frontAndBack+1; ii < num; ++ii)
  4496. {
  4497. uint32_t stencil = unpackStencil(ii, newStencil);
  4498. uint32_t changed = unpackStencil(ii, changedStencil);
  4499. GLenum face = s_stencilFace[frontAndBack+ii];
  4500. if ( (BGFX_STENCIL_TEST_MASK|BGFX_STENCIL_FUNC_REF_MASK|BGFX_STENCIL_FUNC_RMASK_MASK) & changed)
  4501. {
  4502. GLint ref = (stencil&BGFX_STENCIL_FUNC_REF_MASK)>>BGFX_STENCIL_FUNC_REF_SHIFT;
  4503. GLint mask = (stencil&BGFX_STENCIL_FUNC_RMASK_MASK)>>BGFX_STENCIL_FUNC_RMASK_SHIFT;
  4504. uint32_t func = (stencil&BGFX_STENCIL_TEST_MASK)>>BGFX_STENCIL_TEST_SHIFT;
  4505. GL_CHECK(glStencilFuncSeparate(face, s_cmpFunc[func], ref, mask));
  4506. }
  4507. if ( (BGFX_STENCIL_OP_FAIL_S_MASK|BGFX_STENCIL_OP_FAIL_Z_MASK|BGFX_STENCIL_OP_PASS_Z_MASK) & changed)
  4508. {
  4509. uint32_t sfail = (stencil&BGFX_STENCIL_OP_FAIL_S_MASK)>>BGFX_STENCIL_OP_FAIL_S_SHIFT;
  4510. uint32_t zfail = (stencil&BGFX_STENCIL_OP_FAIL_Z_MASK)>>BGFX_STENCIL_OP_FAIL_Z_SHIFT;
  4511. uint32_t zpass = (stencil&BGFX_STENCIL_OP_PASS_Z_MASK)>>BGFX_STENCIL_OP_PASS_Z_SHIFT;
  4512. GL_CHECK(glStencilOpSeparate(face, s_stencilOp[sfail], s_stencilOp[zfail], s_stencilOp[zpass]) );
  4513. }
  4514. }
  4515. }
  4516. else
  4517. {
  4518. GL_CHECK(glDisable(GL_STENCIL_TEST) );
  4519. }
  4520. }
  4521. if ( (0
  4522. | BGFX_STATE_CULL_MASK
  4523. | BGFX_STATE_DEPTH_WRITE
  4524. | BGFX_STATE_DEPTH_TEST_MASK
  4525. | BGFX_STATE_RGB_WRITE
  4526. | BGFX_STATE_ALPHA_WRITE
  4527. | BGFX_STATE_BLEND_MASK
  4528. | BGFX_STATE_BLEND_EQUATION_MASK
  4529. | BGFX_STATE_ALPHA_REF_MASK
  4530. | BGFX_STATE_PT_MASK
  4531. | BGFX_STATE_POINT_SIZE_MASK
  4532. | BGFX_STATE_MSAA
  4533. ) & changedFlags)
  4534. {
  4535. if (BGFX_STATE_CULL_MASK & changedFlags)
  4536. {
  4537. if (BGFX_STATE_CULL_CW & newFlags)
  4538. {
  4539. GL_CHECK(glEnable(GL_CULL_FACE) );
  4540. GL_CHECK(glCullFace(GL_BACK) );
  4541. }
  4542. else if (BGFX_STATE_CULL_CCW & newFlags)
  4543. {
  4544. GL_CHECK(glEnable(GL_CULL_FACE) );
  4545. GL_CHECK(glCullFace(GL_FRONT) );
  4546. }
  4547. else
  4548. {
  4549. GL_CHECK(glDisable(GL_CULL_FACE) );
  4550. }
  4551. }
  4552. if (BGFX_STATE_DEPTH_WRITE & changedFlags)
  4553. {
  4554. GL_CHECK(glDepthMask(!!(BGFX_STATE_DEPTH_WRITE & newFlags) ) );
  4555. }
  4556. if (BGFX_STATE_DEPTH_TEST_MASK & changedFlags)
  4557. {
  4558. uint32_t func = (newFlags&BGFX_STATE_DEPTH_TEST_MASK)>>BGFX_STATE_DEPTH_TEST_SHIFT;
  4559. if (0 != func)
  4560. {
  4561. GL_CHECK(glEnable(GL_DEPTH_TEST) );
  4562. GL_CHECK(glDepthFunc(s_cmpFunc[func]) );
  4563. }
  4564. else
  4565. {
  4566. GL_CHECK(glDisable(GL_DEPTH_TEST) );
  4567. }
  4568. }
  4569. if (BGFX_STATE_ALPHA_REF_MASK & changedFlags)
  4570. {
  4571. uint32_t ref = (newFlags&BGFX_STATE_ALPHA_REF_MASK)>>BGFX_STATE_ALPHA_REF_SHIFT;
  4572. viewState.m_alphaRef = ref/255.0f;
  4573. }
  4574. #if BGFX_CONFIG_RENDERER_OPENGL
  4575. if ( (BGFX_STATE_PT_POINTS|BGFX_STATE_POINT_SIZE_MASK) & changedFlags)
  4576. {
  4577. float pointSize = (float)(bx::uint32_max(1, (newFlags&BGFX_STATE_POINT_SIZE_MASK)>>BGFX_STATE_POINT_SIZE_SHIFT) );
  4578. GL_CHECK(glPointSize(pointSize) );
  4579. }
  4580. if (BGFX_STATE_MSAA & changedFlags)
  4581. {
  4582. if (BGFX_STATE_MSAA & newFlags)
  4583. {
  4584. GL_CHECK(glEnable(GL_MULTISAMPLE) );
  4585. }
  4586. else
  4587. {
  4588. GL_CHECK(glDisable(GL_MULTISAMPLE) );
  4589. }
  4590. }
  4591. #endif // BGFX_CONFIG_RENDERER_OPENGL
  4592. if ( (BGFX_STATE_ALPHA_WRITE|BGFX_STATE_RGB_WRITE) & changedFlags)
  4593. {
  4594. GLboolean alpha = !!(newFlags&BGFX_STATE_ALPHA_WRITE);
  4595. GLboolean rgb = !!(newFlags&BGFX_STATE_RGB_WRITE);
  4596. GL_CHECK(glColorMask(rgb, rgb, rgb, alpha) );
  4597. }
  4598. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK|BGFX_STATE_BLEND_INDEPENDENT) & changedFlags
  4599. || blendFactor != draw.m_rgba)
  4600. {
  4601. if ( (BGFX_STATE_BLEND_MASK|BGFX_STATE_BLEND_EQUATION_MASK|BGFX_STATE_BLEND_INDEPENDENT) & newFlags
  4602. || blendFactor != draw.m_rgba)
  4603. {
  4604. const bool enabled = !!(BGFX_STATE_BLEND_MASK & newFlags);
  4605. const bool independent = !!(BGFX_STATE_BLEND_INDEPENDENT & newFlags)
  4606. && blendIndependentSupported
  4607. ;
  4608. const uint32_t blend = uint32_t( (newFlags&BGFX_STATE_BLEND_MASK)>>BGFX_STATE_BLEND_SHIFT);
  4609. const uint32_t srcRGB = (blend )&0xf;
  4610. const uint32_t dstRGB = (blend>> 4)&0xf;
  4611. const uint32_t srcA = (blend>> 8)&0xf;
  4612. const uint32_t dstA = (blend>>12)&0xf;
  4613. const uint32_t equ = uint32_t((newFlags&BGFX_STATE_BLEND_EQUATION_MASK)>>BGFX_STATE_BLEND_EQUATION_SHIFT);
  4614. const uint32_t equRGB = (equ )&0x7;
  4615. const uint32_t equA = (equ>>3)&0x7;
  4616. const uint32_t numRt = getNumRt();
  4617. if (!BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  4618. || 1 >= numRt
  4619. || !independent)
  4620. {
  4621. if (enabled)
  4622. {
  4623. GL_CHECK(glEnable(GL_BLEND) );
  4624. GL_CHECK(glBlendFuncSeparate(s_blendFactor[srcRGB].m_src
  4625. , s_blendFactor[dstRGB].m_dst
  4626. , s_blendFactor[srcA].m_src
  4627. , s_blendFactor[dstA].m_dst
  4628. ) );
  4629. GL_CHECK(glBlendEquationSeparate(s_blendEquation[equRGB], s_blendEquation[equA]) );
  4630. if ( (s_blendFactor[srcRGB].m_factor || s_blendFactor[dstRGB].m_factor)
  4631. && blendFactor != draw.m_rgba)
  4632. {
  4633. const uint32_t rgba = draw.m_rgba;
  4634. GLclampf rr = ( (rgba>>24) )/255.0f;
  4635. GLclampf gg = ( (rgba>>16)&0xff)/255.0f;
  4636. GLclampf bb = ( (rgba>> 8)&0xff)/255.0f;
  4637. GLclampf aa = ( (rgba )&0xff)/255.0f;
  4638. GL_CHECK(glBlendColor(rr, gg, bb, aa) );
  4639. }
  4640. }
  4641. else
  4642. {
  4643. GL_CHECK(glDisable(GL_BLEND) );
  4644. }
  4645. }
  4646. else
  4647. {
  4648. if (enabled)
  4649. {
  4650. GL_CHECK(glEnablei(GL_BLEND, 0) );
  4651. GL_CHECK(glBlendFuncSeparatei(0
  4652. , s_blendFactor[srcRGB].m_src
  4653. , s_blendFactor[dstRGB].m_dst
  4654. , s_blendFactor[srcA].m_src
  4655. , s_blendFactor[dstA].m_dst
  4656. ) );
  4657. GL_CHECK(glBlendEquationSeparatei(0
  4658. , s_blendEquation[equRGB]
  4659. , s_blendEquation[equA]
  4660. ) );
  4661. }
  4662. else
  4663. {
  4664. GL_CHECK(glDisablei(GL_BLEND, 0) );
  4665. }
  4666. for (uint32_t ii = 1, rgba = draw.m_rgba; ii < numRt; ++ii, rgba >>= 11)
  4667. {
  4668. if (0 != (rgba&0x7ff) )
  4669. {
  4670. const uint32_t src = (rgba )&0xf;
  4671. const uint32_t dst = (rgba>>4)&0xf;
  4672. const uint32_t equation = (rgba>>8)&0x7;
  4673. GL_CHECK(glEnablei(GL_BLEND, ii) );
  4674. GL_CHECK(glBlendFunci(ii, s_blendFactor[src].m_src, s_blendFactor[dst].m_dst) );
  4675. GL_CHECK(glBlendEquationi(ii, s_blendEquation[equation]) );
  4676. }
  4677. else
  4678. {
  4679. GL_CHECK(glDisablei(GL_BLEND, ii) );
  4680. }
  4681. }
  4682. }
  4683. }
  4684. else
  4685. {
  4686. GL_CHECK(glDisable(GL_BLEND) );
  4687. }
  4688. blendFactor = draw.m_rgba;
  4689. }
  4690. const uint64_t pt = _render->m_debug&BGFX_DEBUG_WIREFRAME ? BGFX_STATE_PT_LINES : newFlags&BGFX_STATE_PT_MASK;
  4691. primIndex = uint8_t(pt>>BGFX_STATE_PT_SHIFT);
  4692. prim = s_primInfo[primIndex];
  4693. }
  4694. bool programChanged = false;
  4695. bool constantsChanged = draw.m_constBegin < draw.m_constEnd;
  4696. bool bindAttribs = false;
  4697. rendererUpdateUniforms(this, _render->m_constantBuffer, draw.m_constBegin, draw.m_constEnd);
  4698. if (key.m_program != programIdx)
  4699. {
  4700. programIdx = key.m_program;
  4701. GLuint id = invalidHandle == programIdx ? 0 : m_program[programIdx].m_id;
  4702. // Skip rendering if program index is valid, but program is invalid.
  4703. programIdx = 0 == id ? invalidHandle : programIdx;
  4704. GL_CHECK(glUseProgram(id) );
  4705. programChanged =
  4706. constantsChanged =
  4707. bindAttribs = true;
  4708. }
  4709. if (invalidHandle != programIdx)
  4710. {
  4711. ProgramGL& program = m_program[programIdx];
  4712. if (constantsChanged
  4713. && NULL != program.m_constantBuffer)
  4714. {
  4715. commit(*program.m_constantBuffer);
  4716. }
  4717. viewState.setPredefined<1>(this, view, eye, program, _render, draw);
  4718. {
  4719. for (uint32_t stage = 0; stage < BGFX_CONFIG_MAX_TEXTURE_SAMPLERS; ++stage)
  4720. {
  4721. const Binding& sampler = draw.m_bind[stage];
  4722. Binding& current = currentState.m_bind[stage];
  4723. if (current.m_idx != sampler.m_idx
  4724. || current.m_un.m_draw.m_flags != sampler.m_un.m_draw.m_flags
  4725. || programChanged)
  4726. {
  4727. if (invalidHandle != sampler.m_idx)
  4728. {
  4729. TextureGL& texture = m_textures[sampler.m_idx];
  4730. texture.commit(stage, sampler.m_un.m_draw.m_flags);
  4731. }
  4732. }
  4733. current = sampler;
  4734. }
  4735. }
  4736. if (0 != defaultVao
  4737. && 0 == draw.m_startVertex
  4738. && 0 == draw.m_instanceDataOffset)
  4739. {
  4740. if (programChanged
  4741. || baseVertex != draw.m_startVertex
  4742. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  4743. || currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx
  4744. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  4745. || currentState.m_instanceDataStride != draw.m_instanceDataStride
  4746. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx)
  4747. {
  4748. bx::HashMurmur2A murmur;
  4749. murmur.begin();
  4750. murmur.add(draw.m_vertexBuffer.idx);
  4751. if (isValid(draw.m_vertexBuffer) )
  4752. {
  4753. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4754. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4755. murmur.add(decl);
  4756. }
  4757. murmur.add(draw.m_indexBuffer.idx);
  4758. murmur.add(draw.m_instanceDataBuffer.idx);
  4759. murmur.add(draw.m_instanceDataOffset);
  4760. murmur.add(draw.m_instanceDataStride);
  4761. murmur.add(programIdx);
  4762. uint32_t hash = murmur.end();
  4763. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  4764. currentState.m_indexBuffer = draw.m_indexBuffer;
  4765. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  4766. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  4767. baseVertex = draw.m_startVertex;
  4768. GLuint id = m_vaoStateCache.find(hash);
  4769. if (UINT32_MAX != id)
  4770. {
  4771. currentVao = id;
  4772. GL_CHECK(glBindVertexArray(id) );
  4773. }
  4774. else
  4775. {
  4776. id = m_vaoStateCache.add(hash);
  4777. currentVao = id;
  4778. GL_CHECK(glBindVertexArray(id) );
  4779. program.add(hash);
  4780. if (isValid(draw.m_vertexBuffer) )
  4781. {
  4782. VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4783. vb.add(hash);
  4784. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  4785. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4786. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  4787. if (isValid(draw.m_instanceDataBuffer) )
  4788. {
  4789. VertexBufferGL& instanceVb = m_vertexBuffers[draw.m_instanceDataBuffer.idx];
  4790. instanceVb.add(hash);
  4791. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, instanceVb.m_id) );
  4792. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  4793. }
  4794. }
  4795. else
  4796. {
  4797. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  4798. }
  4799. if (isValid(draw.m_indexBuffer) )
  4800. {
  4801. IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  4802. ib.add(hash);
  4803. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  4804. }
  4805. else
  4806. {
  4807. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  4808. }
  4809. }
  4810. }
  4811. }
  4812. else
  4813. {
  4814. if (0 != defaultVao
  4815. && 0 != currentVao)
  4816. {
  4817. GL_CHECK(glBindVertexArray(defaultVao) );
  4818. currentState.m_vertexBuffer.idx = invalidHandle;
  4819. currentState.m_indexBuffer.idx = invalidHandle;
  4820. bindAttribs = true;
  4821. currentVao = 0;
  4822. }
  4823. if (programChanged
  4824. || currentState.m_vertexBuffer.idx != draw.m_vertexBuffer.idx
  4825. || currentState.m_instanceDataBuffer.idx != draw.m_instanceDataBuffer.idx
  4826. || currentState.m_instanceDataOffset != draw.m_instanceDataOffset
  4827. || currentState.m_instanceDataStride != draw.m_instanceDataStride)
  4828. {
  4829. currentState.m_vertexBuffer = draw.m_vertexBuffer;
  4830. currentState.m_instanceDataBuffer.idx = draw.m_instanceDataBuffer.idx;
  4831. currentState.m_instanceDataOffset = draw.m_instanceDataOffset;
  4832. currentState.m_instanceDataStride = draw.m_instanceDataStride;
  4833. uint16_t handle = draw.m_vertexBuffer.idx;
  4834. if (invalidHandle != handle)
  4835. {
  4836. VertexBufferGL& vb = m_vertexBuffers[handle];
  4837. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, vb.m_id) );
  4838. bindAttribs = true;
  4839. }
  4840. else
  4841. {
  4842. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, 0) );
  4843. }
  4844. }
  4845. if (currentState.m_indexBuffer.idx != draw.m_indexBuffer.idx)
  4846. {
  4847. currentState.m_indexBuffer = draw.m_indexBuffer;
  4848. uint16_t handle = draw.m_indexBuffer.idx;
  4849. if (invalidHandle != handle)
  4850. {
  4851. IndexBufferGL& ib = m_indexBuffers[handle];
  4852. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib.m_id) );
  4853. }
  4854. else
  4855. {
  4856. GL_CHECK(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) );
  4857. }
  4858. }
  4859. if (isValid(currentState.m_vertexBuffer) )
  4860. {
  4861. if (baseVertex != draw.m_startVertex
  4862. || bindAttribs)
  4863. {
  4864. baseVertex = draw.m_startVertex;
  4865. const VertexBufferGL& vb = m_vertexBuffers[draw.m_vertexBuffer.idx];
  4866. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4867. program.bindAttributes(m_vertexDecls[decl], draw.m_startVertex);
  4868. if (isValid(draw.m_instanceDataBuffer) )
  4869. {
  4870. GL_CHECK(glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffers[draw.m_instanceDataBuffer.idx].m_id) );
  4871. program.bindInstanceData(draw.m_instanceDataStride, draw.m_instanceDataOffset);
  4872. }
  4873. }
  4874. }
  4875. }
  4876. if (isValid(currentState.m_vertexBuffer) )
  4877. {
  4878. uint32_t numVertices = draw.m_numVertices;
  4879. if (UINT32_MAX == numVertices)
  4880. {
  4881. const VertexBufferGL& vb = m_vertexBuffers[currentState.m_vertexBuffer.idx];
  4882. uint16_t decl = !isValid(vb.m_decl) ? draw.m_vertexDecl.idx : vb.m_decl.idx;
  4883. const VertexDecl& vertexDecl = m_vertexDecls[decl];
  4884. numVertices = vb.m_size/vertexDecl.m_stride;
  4885. }
  4886. uint32_t numIndices = 0;
  4887. uint32_t numPrimsSubmitted = 0;
  4888. uint32_t numInstances = 0;
  4889. uint32_t numPrimsRendered = 0;
  4890. uint32_t numDrawIndirect = 0;
  4891. if (isValid(draw.m_indirectBuffer) )
  4892. {
  4893. const VertexBufferGL& vb = m_vertexBuffers[draw.m_indirectBuffer.idx];
  4894. if (currentState.m_indirectBuffer.idx != draw.m_indirectBuffer.idx)
  4895. {
  4896. currentState.m_indirectBuffer = draw.m_indirectBuffer;
  4897. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, vb.m_id) );
  4898. }
  4899. if (isValid(draw.m_indexBuffer) )
  4900. {
  4901. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  4902. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  4903. const GLenum indexFormat = hasIndex16
  4904. ? GL_UNSIGNED_SHORT
  4905. : GL_UNSIGNED_INT
  4906. ;
  4907. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  4908. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4909. : draw.m_numIndirect
  4910. ;
  4911. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4912. GL_CHECK(glMultiDrawElementsIndirect(prim.m_type, indexFormat
  4913. , (void*)args
  4914. , numDrawIndirect
  4915. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4916. ) );
  4917. }
  4918. else
  4919. {
  4920. numDrawIndirect = UINT16_MAX == draw.m_numIndirect
  4921. ? vb.m_size/BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4922. : draw.m_numIndirect
  4923. ;
  4924. uintptr_t args = draw.m_startIndirect * BGFX_CONFIG_DRAW_INDIRECT_STRIDE;
  4925. GL_CHECK(glMultiDrawArraysIndirect(prim.m_type
  4926. , (void*)args
  4927. , numDrawIndirect
  4928. , BGFX_CONFIG_DRAW_INDIRECT_STRIDE
  4929. ) );
  4930. }
  4931. }
  4932. else
  4933. {
  4934. if (isValid(currentState.m_indirectBuffer) )
  4935. {
  4936. currentState.m_indirectBuffer.idx = invalidHandle;
  4937. GL_CHECK(glBindBuffer(GL_DRAW_INDIRECT_BUFFER, 0) );
  4938. }
  4939. if (isValid(draw.m_indexBuffer) )
  4940. {
  4941. const IndexBufferGL& ib = m_indexBuffers[draw.m_indexBuffer.idx];
  4942. const bool hasIndex16 = 0 == (ib.m_flags & BGFX_BUFFER_INDEX32);
  4943. const uint32_t indexSize = hasIndex16 ? 2 : 4;
  4944. const GLenum indexFormat = hasIndex16
  4945. ? GL_UNSIGNED_SHORT
  4946. : GL_UNSIGNED_INT
  4947. ;
  4948. if (UINT32_MAX == draw.m_numIndices)
  4949. {
  4950. numIndices = ib.m_size/indexSize;
  4951. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  4952. numInstances = draw.m_numInstances;
  4953. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  4954. GL_CHECK(glDrawElementsInstanced(prim.m_type
  4955. , numIndices
  4956. , indexFormat
  4957. , (void*)0
  4958. , draw.m_numInstances
  4959. ) );
  4960. }
  4961. else if (prim.m_min <= draw.m_numIndices)
  4962. {
  4963. numIndices = draw.m_numIndices;
  4964. numPrimsSubmitted = numIndices/prim.m_div - prim.m_sub;
  4965. numInstances = draw.m_numInstances;
  4966. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  4967. GL_CHECK(glDrawElementsInstanced(prim.m_type
  4968. , numIndices
  4969. , indexFormat
  4970. , (void*)(uintptr_t)(draw.m_startIndex*indexSize)
  4971. , draw.m_numInstances
  4972. ) );
  4973. }
  4974. }
  4975. else
  4976. {
  4977. numPrimsSubmitted = numVertices/prim.m_div - prim.m_sub;
  4978. numInstances = draw.m_numInstances;
  4979. numPrimsRendered = numPrimsSubmitted*draw.m_numInstances;
  4980. GL_CHECK(glDrawArraysInstanced(prim.m_type
  4981. , 0
  4982. , numVertices
  4983. , draw.m_numInstances
  4984. ) );
  4985. }
  4986. }
  4987. statsNumPrimsSubmitted[primIndex] += numPrimsSubmitted;
  4988. statsNumPrimsRendered[primIndex] += numPrimsRendered;
  4989. statsNumInstances[primIndex] += numInstances;
  4990. statsNumIndices += numIndices;
  4991. }
  4992. }
  4993. }
  4994. blitMsaaFbo();
  4995. if (0 < _render->m_num)
  4996. {
  4997. if (0 != (m_resolution.m_flags & BGFX_RESET_FLUSH_AFTER_RENDER) )
  4998. {
  4999. GL_CHECK(glFlush() );
  5000. }
  5001. captureElapsed = -bx::getHPCounter();
  5002. capture();
  5003. captureElapsed += bx::getHPCounter();
  5004. }
  5005. }
  5006. m_glctx.makeCurrent(NULL);
  5007. int64_t now = bx::getHPCounter();
  5008. elapsed += now;
  5009. static int64_t last = now;
  5010. int64_t frameTime = now - last;
  5011. last = now;
  5012. static int64_t min = frameTime;
  5013. static int64_t max = frameTime;
  5014. min = min > frameTime ? frameTime : min;
  5015. max = max < frameTime ? frameTime : max;
  5016. if (_render->m_debug & (BGFX_DEBUG_IFH|BGFX_DEBUG_STATS) )
  5017. {
  5018. double elapsedGpuMs = 0.0;
  5019. uint64_t elapsedGl = 0;
  5020. if (BX_ENABLED(BGFX_CONFIG_RENDERER_OPENGL)
  5021. && m_timerQuerySupport)
  5022. {
  5023. m_queries.end(GL_TIME_ELAPSED);
  5024. elapsedGl = m_queries.getResult(0);
  5025. elapsedGpuMs = double(elapsedGl)/1e6;
  5026. }
  5027. TextVideoMem& tvm = m_textVideoMem;
  5028. static int64_t next = now;
  5029. if (now >= next)
  5030. {
  5031. next = now + bx::getHPFrequency();
  5032. double freq = double(bx::getHPFrequency() );
  5033. double toMs = 1000.0/freq;
  5034. tvm.clear();
  5035. uint16_t pos = 0;
  5036. tvm.printf(0, pos++, BGFX_CONFIG_DEBUG ? 0x89 : 0x8f, " %s / " BX_COMPILER_NAME " / " BX_CPU_NAME " / " BX_ARCH_NAME " / " BX_PLATFORM_NAME " "
  5037. , getRendererName()
  5038. );
  5039. tvm.printf(0, pos++, 0x0f, " Vendor: %s", m_vendor);
  5040. tvm.printf(0, pos++, 0x0f, " Renderer: %s", m_renderer);
  5041. tvm.printf(0, pos++, 0x0f, " Version: %s", m_version);
  5042. tvm.printf(0, pos++, 0x0f, "GLSL version: %s", m_glslVersion);
  5043. pos = 10;
  5044. tvm.printf(10, pos++, 0x8e, " Frame CPU: %7.3f, % 7.3f \x1f, % 7.3f \x1e [ms] / % 6.2f FPS "
  5045. , double(frameTime)*toMs
  5046. , double(min)*toMs
  5047. , double(max)*toMs
  5048. , freq/frameTime
  5049. );
  5050. char hmd[16];
  5051. bx::snprintf(hmd, BX_COUNTOF(hmd), ", [%c] HMD ", hmdEnabled ? '\xfe' : ' ');
  5052. const uint32_t msaa = (m_resolution.m_flags&BGFX_RESET_MSAA_MASK)>>BGFX_RESET_MSAA_SHIFT;
  5053. tvm.printf(10, pos++, 0x8e, " Reset flags: [%c] vsync, [%c] MSAAx%d%s, [%c] MaxAnisotropy "
  5054. , !!(m_resolution.m_flags&BGFX_RESET_VSYNC) ? '\xfe' : ' '
  5055. , 0 != msaa ? '\xfe' : ' '
  5056. , 1<<msaa
  5057. , m_ovr.isInitialized() ? hmd : ", no-HMD "
  5058. , !!(m_resolution.m_flags&BGFX_RESET_MAXANISOTROPY) ? '\xfe' : ' '
  5059. );
  5060. double elapsedCpuMs = double(elapsed)*toMs;
  5061. tvm.printf(10, pos++, 0x8e, " Submitted: %4d (draw %4d, compute %4d) / CPU %3.4f [ms] %c GPU %3.4f [ms]"
  5062. , _render->m_num
  5063. , statsKeyType[0]
  5064. , statsKeyType[1]
  5065. , elapsedCpuMs
  5066. , elapsedCpuMs > elapsedGpuMs ? '>' : '<'
  5067. , elapsedGpuMs
  5068. );
  5069. for (uint32_t ii = 0; ii < BX_COUNTOF(s_primInfo); ++ii)
  5070. {
  5071. tvm.printf(10, pos++, 0x8e, " %9s: %7d (#inst: %5d), submitted: %7d"
  5072. , s_primName[ii]
  5073. , statsNumPrimsRendered[ii]
  5074. , statsNumInstances[ii]
  5075. , statsNumPrimsSubmitted[ii]
  5076. );
  5077. }
  5078. if (NULL != m_renderdocdll)
  5079. {
  5080. tvm.printf(tvm.m_width-27, 0, 0x1f, " [F11 - RenderDoc capture] ");
  5081. }
  5082. tvm.printf(10, pos++, 0x8e, " Indices: %7d", statsNumIndices);
  5083. tvm.printf(10, pos++, 0x8e, " DVB size: %7d", _render->m_vboffset);
  5084. tvm.printf(10, pos++, 0x8e, " DIB size: %7d", _render->m_iboffset);
  5085. pos++;
  5086. tvm.printf(10, pos++, 0x8e, " State cache: ");
  5087. tvm.printf(10, pos++, 0x8e, " VAO | Sampler ");
  5088. tvm.printf(10, pos++, 0x8e, " %6d | %6d "
  5089. , m_vaoStateCache.getCount()
  5090. , m_samplerStateCache.getCount()
  5091. );
  5092. pos++;
  5093. double captureMs = double(captureElapsed)*toMs;
  5094. tvm.printf(10, pos++, 0x8e, " Capture: %3.4f [ms]", captureMs);
  5095. #if BGFX_CONFIG_RENDERER_OPENGL
  5096. if (s_extension[Extension::ATI_meminfo].m_supported)
  5097. {
  5098. GLint vboFree[4];
  5099. GL_CHECK(glGetIntegerv(GL_VBO_FREE_MEMORY_ATI, vboFree) );
  5100. GLint texFree[4];
  5101. GL_CHECK(glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, texFree) );
  5102. GLint rbfFree[4];
  5103. GL_CHECK(glGetIntegerv(GL_RENDERBUFFER_FREE_MEMORY_ATI, rbfFree) );
  5104. pos++;
  5105. tvm.printf(10, pos++, 0x8c, " -------------| free| free b| aux| aux fb");
  5106. char tmp0[16];
  5107. char tmp1[16];
  5108. char tmp2[16];
  5109. char tmp3[16];
  5110. bx::prettify(tmp0, BX_COUNTOF(tmp0), vboFree[0]);
  5111. bx::prettify(tmp1, BX_COUNTOF(tmp1), vboFree[1]);
  5112. bx::prettify(tmp2, BX_COUNTOF(tmp2), vboFree[2]);
  5113. bx::prettify(tmp3, BX_COUNTOF(tmp3), vboFree[3]);
  5114. tvm.printf(10, pos++, 0x8e, " VBO: %10s, %10s, %10s, %10s", tmp0, tmp1, tmp2, tmp3);
  5115. bx::prettify(tmp0, BX_COUNTOF(tmp0), texFree[0]);
  5116. bx::prettify(tmp1, BX_COUNTOF(tmp1), texFree[1]);
  5117. bx::prettify(tmp2, BX_COUNTOF(tmp2), texFree[2]);
  5118. bx::prettify(tmp3, BX_COUNTOF(tmp3), texFree[3]);
  5119. tvm.printf(10, pos++, 0x8e, " Texture: %10s, %10s, %10s, %10s", tmp0, tmp1, tmp2, tmp3);
  5120. bx::prettify(tmp0, BX_COUNTOF(tmp0), rbfFree[0]);
  5121. bx::prettify(tmp1, BX_COUNTOF(tmp1), rbfFree[1]);
  5122. bx::prettify(tmp2, BX_COUNTOF(tmp2), rbfFree[2]);
  5123. bx::prettify(tmp3, BX_COUNTOF(tmp3), rbfFree[3]);
  5124. tvm.printf(10, pos++, 0x8e, " Render Buffer: %10s, %10s, %10s, %10s", tmp0, tmp1, tmp2, tmp3);
  5125. }
  5126. else if (s_extension[Extension::NVX_gpu_memory_info].m_supported)
  5127. {
  5128. GLint dedicated;
  5129. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_DEDICATED_VIDMEM_NVX, &dedicated) );
  5130. GLint totalAvail;
  5131. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &totalAvail) );
  5132. GLint currAvail;
  5133. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &currAvail) );
  5134. GLint evictedCount;
  5135. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTION_COUNT_NVX, &evictedCount) );
  5136. GLint evictedMemory;
  5137. GL_CHECK(glGetIntegerv(GL_GPU_MEMORY_INFO_EVICTED_MEMORY_NVX, &evictedMemory) );
  5138. pos += 2;
  5139. char tmp0[16];
  5140. char tmp1[16];
  5141. bx::prettify(tmp0, BX_COUNTOF(tmp0), dedicated);
  5142. tvm.printf(10, pos++, 0x8e, " Dedicated: %10s", tmp0);
  5143. bx::prettify(tmp0, BX_COUNTOF(tmp0), currAvail);
  5144. bx::prettify(tmp1, BX_COUNTOF(tmp1), totalAvail);
  5145. tvm.printf(10, pos++, 0x8e, " Available: %10s / %10s", tmp0, tmp1);
  5146. bx::prettify(tmp0, BX_COUNTOF(tmp0), evictedCount);
  5147. bx::prettify(tmp1, BX_COUNTOF(tmp1), evictedMemory);
  5148. tvm.printf(10, pos++, 0x8e, " Eviction: %10s / %10s", tmp0, tmp1);
  5149. }
  5150. #endif // BGFX_CONFIG_RENDERER_OPENGL
  5151. uint8_t attr[2] = { 0x89, 0x8a };
  5152. uint8_t attrIndex = _render->m_waitSubmit < _render->m_waitRender;
  5153. pos++;
  5154. tvm.printf(10, pos++, attr[attrIndex&1], "Submit wait: %3.4f [ms]", double(_render->m_waitSubmit)*toMs);
  5155. tvm.printf(10, pos++, attr[(attrIndex+1)&1], "Render wait: %3.4f [ms]", double(_render->m_waitRender)*toMs);
  5156. min = frameTime;
  5157. max = frameTime;
  5158. }
  5159. blit(this, _textVideoMemBlitter, tvm);
  5160. }
  5161. else if (_render->m_debug & BGFX_DEBUG_TEXT)
  5162. {
  5163. blit(this, _textVideoMemBlitter, _render->m_textVideoMem);
  5164. }
  5165. GL_CHECK(glFrameTerminatorGREMEDY() );
  5166. }
  5167. } } // namespace bgfx
  5168. #else
  5169. namespace bgfx { namespace gl
  5170. {
  5171. RendererContextI* rendererCreate()
  5172. {
  5173. return NULL;
  5174. }
  5175. void rendererDestroy()
  5176. {
  5177. }
  5178. } /* namespace gl */ } // namespace bgfx
  5179. #endif // (BGFX_CONFIG_RENDERER_OPENGLES || BGFX_CONFIG_RENDERER_OPENGL)