renderer_gl.cpp 228 KB

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