renderer_gl.cpp 233 KB

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