renderer_gl.cpp 232 KB

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