renderer_gl.cpp 256 KB

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