renderer_gl.cpp 237 KB

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